big_ugly_variable = big_ugly_variable + 1
is tedious.
We have a better way:
a+=b
is the same as a = a+b
a-=b
is the same as a = a-b
a*=b
is the same as a = a*b
a/=b
is the same as a = a/b
a%=b
is the same as a = a%b
The expressions can be arbitrarily complex:
a+=a+b*c
is the same as a = 2*a + b*c
Adding or subtracting one (incrementing/decrementing) is so common, that we have special notations for just that:
++
: Increment a variable
--
: Decrement a variable
++i
, or after, i++
, the variable.
These two expressions have different behaviors.
++i
, causes the variable
to be incremented before it is used in the expression that contains it.
i++,
causes the variable to be incremented after it
is used in its containing expression.
int foo, i=2; foo = i++; printf("foo=%d i=%d\n", foo, i); foo = ++i; printf("foo=%d i=%d\n", foo, i); foo = i--; printf("foo=%d i=%d\n", foo, i); foo = --i; printf("foo=%d i=%d\n", foo, i);
foo=2 i=3 foo=4 i=4 foo=4 i=3 foo=2 i=2
The variable i
takes the values 2, 3, 4, 3, 2 as expected, but its value
is updated at different times depending on pre-increment or post-increment.
i = i++; i++ * i++; i = --i - i--;
i++; j = i++; for (i=0; i<5; i++)
i = i++;
, or using
an uninitialized variable, are undefined behavior.