Friday, January 6, 2012

What are the meanings of operators ++, --, and % ?

The operator ++ is an increment operator, which can be placed before or after (but not both) a variable. The operator will increase the value of the variable by 1. For example, assuming a variable i is equal to 1, then after the statement

i++;

or

++i;

is executed, the value of i is 2 (i++ is not exactly the same as ++i).

Note that the C statement

i++;

or

++i;

can be understood as the statement

i = i + 1;

which also causes the value of the variable i to increase by 1. Similarly, the operator -- is a decrement operator, which decreases the value of a variable by 1. Also, the statement

i--;

or

--i;

can be understood as the statement

i = i - 1;

The operator % is a remainder operator, which must be placed between two integer variables or constants. Assuming k and p are two integer variables, the meaning of k%p is the remainder of k divided by p. For example, if k = 11 and p = 3, then k%p is equivalent 11%3, which is equal to 2 (because 3 goes into 11 three times with a remainder of 2). The operator % is pronounced "mod." So this example would be k mod p. ANSI C states that, if either operand is negative, the sign of the result of the % operation is implementation defined; that is, it is free for the C compiler designer to decide. For example, depending on the compiler you use, the results of -50 % 6 and 50 % (-6) may be 2 or -2.

No comments:

Post a Comment