These operators include:
-Autoincrement and autodecrement operators-Compound assignment operators-Comma operator-Conditional expression operator
i++ => i = i + 1
i-- => i = i - 1
These are post increment and post decrement operators. In general, they take the form:
<Lvalue>++
<Lvalue>--
We can also have pre increment and pre decrement operators.
++i => i = i + 1
--i => i = i - 1
The difference is that the "post" operators evaluate to the value of i before the update; while the "pre" operators evaluate the the value if i after the update.
For example:
i = j = 1;
if( i++ > 1) ...
is false, but
if( ++j > 1) ...
is true.
The autoincrement/decrement operators always add a constant 1 to the variable. We can make this an arbitrary value with the compound assignment operators:
k += 5 => k = k + 5
w -= 10 => w = w - 10
x *= b => x = x * b
y /= a+b => y = y / (a+b)
x %= 10 => x = x % 10
(also <<, >>, &, ^, | operators)
In general, these take the form
<Lvalue> <op>= <expression>
equivalent to
<Lvalue> = <Lvalue> <op> ( <expression> )
The comma operators is a way to combine two expressions to act as one, of the form:
<expression 1> , <expression2>
This "comma" expression evaluates the the value of the last expression. For example:
f( a, (t = 4, t += 2), 9)
calls the function, f(), passing three values: a, 6, and 9.
The comma operator is most often used in for loops. For example, we can rewrite our factorial function more compactly as:
int factorial( int n)
{ int prod;
int j;
for( (prod=1,j=1); j <= n; j++)
prod *= j;
return prod;
}
We have seen the if statement:
if ( <condition> ) <statement 1> [else <statement 2>]
but this "statement" has no value. C provides a conditional expression which can conditionally evaluate to a value:
<condition> ? <expression 1> : <expression 2>
which evaluates to <expression 1> if <condition> is true, otherwise to <expression 2>.
We might use this expression in place of a function call for absolute:
x = (x < 0) ? -x : x;
or better, define a macro:
#define ABSOLUTE(x) (((x) < 0) ? -(x) : (x))
and write
diff = ABSOLUTE(diff);