Introduction to operators and functions

Precedence and Associativity of Operators

Precedence:

The order of evaluation in an expression involving several operators (i.e / * + -),depends on the priority or precedence they have. For example operators *, / and % have higher precedence than the operators +,-. The operators *, / and % have same precedence and operators + and - have same precedence. For example, in the statement


8-2*3;

2*3 is evaluated before and the result of 2*3 is subtracted from 8. Thus you always need to be careful when writing c++ expressions involving these operators.

parenthesesYou can actually use parentheses to force the program to output the desired results. Always use parentheses when you are not sure of the precedence of the operators in an expression.
Using parentheses the above example can be forced to evaluate correctly as follows
(8-(2*3));


As indicated, the natural order of execution of the operators is overridden by the parentheses. Parentheses are given more priority than the any of the operators forcing the operations to have higher precedence. In an expression with nested parentheses, the innermost parentheses are evaluated first and so the expression 2*(3+1), 3+1 is evaluated first even if the multiplication operator has a higher precedence.

Associativity:
When several operators of same precedence are in an expression, they can be are evaluated either from left-to-right (left associative) or right-to-left (right associative). Left associative means that left most operators are evaluated first then the operators on the right. Right associative means that right most operators are evaluated first than the operators on the left. If the expression a+b+c is evaluated in the left associative manner, then result of a+b is added to c. Similarly in the right associative, result of b+c is added to a.
Left-to-right associativity means that if two operators acting on the same operand have the same precedence, you apply the left-hand operator first. For right-to-left associativity, you apply the right-hand operator first. Below is a table of operators and their respective associativity order.

Operator NameAssociativityOperators
Primary scope resolution left to right ::
Assignment right to left= += -= *= /= <<= >>= %= &= ^= |=
Primary left to right () [ ] . -> dynamic_cast typeid
Unary right to left ++ -- + - ! ~ & * (type_name) sizeof new delete
C++ Pointer to Memberleft to right .*->*
Multiplicative left to right * / %
Additive left to right+ -
Bitwise Shift left to right<< >>
Relational left to right < > <= >=
Equality left to right == !=
Bitwise AND left to right &
Bitwise Exclusive OR left to right ^
Bitwise Inclusive OR left to right |
Logical AND left to right &&
Logical OR left to right||
Conditional right to left? :





Introduction to functions

C++ Functions, otherwise called methods or procedures in other programming languages make it easy to modularize a program by separating its tasks into self-contained units. One example is main function int main(), which we have used right from the beginning. Because functions are written by the programmers, they are sometimes referred to as user-defined functions or programmer-defined functions. In definition terms, a function is a block of statements that execute when called from some point of the program. The statements in the body of the function are written once and are reused from several locations in a program. Function statements are hidden from other functions.

Declaration of functions

To declare a function you specify first its return type, i.e. the data type to be returned by the function. The return type is followed by the name or the identifier by which the function will be called. The function name is followed by a pair of parentheses. Inside the the pair of parentheses also know as the parameter list area, can be left empty implying that the function will not receive any arguments or can include as many parameters as needed. If parameters are used each must have a data type specifier followed by a name (an identifier). Parameters act within the function as a regular local variable and they are thus declared as such (for example: int myAge). Parameters are used as variable aliases thus allowing the programmer to pass arguments in the calling function. Parameters are separated by a comma. The body of a function is surrounded by braces. Below is an example of a function declaration.

type name ( type par1, type par2, ...) 

{ 

statement 

} 


Where type is the data type to be returned (it can be int,char,float, double, string, user defined type, etc), name is the identifier while par1and par2 are parameters. Statement is a block of statements within the body of the function, i.e. all that is surrounded by braces { }.
Here is an example of a function in practice:

1 //ProductOfSubAndAdd function example

2 #include

3 using namespace std;

4 int ProductOfSubAndAdd (int small, int big)

5 {

6 int add;

7 int subt;

8 add=small+big;

9 subt=big-small;

10 int multp=add*subt;

11 return multp;

12 }

Output: The result of (2 +4) times (4-2) is 12.

We begin by examining the function ProductOfSubAndAdd. This function declares int as its return type and an identifier/name ProductOfSubAndAdd. Two parameters small and big both of the type int are included in the parameter list. In the body of the function three local variables add, subt and product are declared. Using an expression, sum is assigned the sum of small and big as in sum=small+small.

Similarly, variable subt is assigned the difference between big and small as in subt=big-small. The results of sum and subt are multiplied and the answer is assigned to multp, i.e. multp=add*subt. The function then returns the data stored in multp, which is the value that will be required by the calling function, which in our case is function main().

Function main begins by declaring the variable product of type int. Right after that, a call to function ProductOfSubAndAdd is made with arguments 2 and 4. The result returned by function ProductOfSubAndAdd is assigned to variable product as in product=ProductOfSubAndAdd(2,4). This result is then displayed using cout.

When a function is called, it executes its statements and where parameters are used, it uses the arguments passed to it to produce a result . When the function is ready, it return its result to the caller. In our case function ProductOfSubAndAdd returns the result to main. Function main returns 0 indicating that everything was successful.


Function Prototypes

A function prototype also known as a function declaration tells the compiler the name of a function, the data type to be returned by that function, the number and type of parameters the function expects to receive, and the order in which the parameters are expected. The function prototype is declared first, if it is to be invoked before its definition. Where a function is already included in a separate file, its prototype should be included in the header files so as to inform the compiler that the function will be used.You can use the #include"filename" to instruct the compiler to obtain your function in a particular file. However if the function is to be invoked after it has been defined, it is not necessary to indicate first its prototype.
For a function saved elsewhere, include the prototype in the header as follows
#include "filename"
if you want want to invoke the function before you define it, just include it somewhere after the header files, for examples as follows
string myName(string firstName, string lastName);

Function Signitures

Diagram showing signiture section of a function
Function Signiture

As indicated in the diagram above, the function signature is that portion of its prototype excluding the return type. It includes the name of the function and its arguments. Functions in the same scope or the region of a program in which the function is known and accessible must have unique signatures. A compiler reports an error, if within the scope there is a function of the same signature with a different return type. For example
string myName(string firstName, string lastName) would not compiler if within the same scope there is another function stated as: void myName(string firstName, string lastName) Similarly,a call to such prottypes would cause a compiler error because void refers to no return while string indicates to the compiler that data of type string is to be returned.

Argument Coercion

A function can be forced to be called with argument types not specified in its parameter declarations. This is refered to as Argument Coersion. For example, a program can call a function with a double argument, even though its declaration prototype specifies an int parameter type. The function will still work correctly.

Argument Promotion Rules

Arguments do not always correspond precisely with the parameter types in the function prototype. In such a situation inconsistent arguments are converted to the proper type before the function is called. However such conversions could lead to incorrect results if not properly converted. This is where function promotion rules come in handy.

The rules specify how types can be converted to other types without losing data. Normally, an expression containing variables of different types, the low type say an int is automatically converted to a higher one say a double without losing the original value stored in a variable. Promotion rules apply to expressions containing values of two or more data types; such expressions are also referred to as mixed-type expressions. However, if a higher type, say a double, is converted to a lower one, say an int, the fractional part of value stored in the variable will be truncated leading to a loss of accuracy. Some compilers will actually issue an error message if a conversion from a higher to a lower type is done. As a matter of caution, converting from a large to a small type (i.e. int to char, long to short) can result in changed values.   See an example of using static_cast to avoid trancating

The type of each value in a mixed-type expression is promoted to the "highest" type in the expression. Another common use of promotion is when the type of an argument to a function does not match the parameter type specified in the function definition.

List of the built-in data types in their hierarchical order from "lowest to highest”

Lowest to highest Type Equivalent name
1 Char -
2 short -
3 unsigned Char
4 short int short
5 unsigned short int unsignd short
6 int
7 unsigned int equivalent to unsigned
8 long int Long
9 unsigned long int Unsigned long
10 float -
11 double -
12 long double -


Void Function Or Function with no Return Type

The functions we have seen sofar appear as

type name ( argument1, argument2 ...) { statement }

As you can see the declaration begins with a data type to be returned. But at times a function may not need to return any value. For example a function that just displays a message on the screen does do not have to return any value. To specify that a function does not return a value, we use the void type specifier for the function to indicate to the compiler of the absence of the return type.See an example of functions using void and passing by values   See also a detailed Example on parameter and void functions
PREV:Introduction to Pointers NEXT:introduction to scope rules of names or identifiers

No comments:

Post a Comment