It’s tedious to say
big_ugly_variable = big_ugly_variable + 1
,
so we have a better way to do that sort of thing:
a+=b
⇒ a = a+b
a-=b
⇒ a = a-b
a*=b
⇒ a = a*b
a/=b
⇒ a = a/b
a%=b
⇒ a = a%b
The expressions can be arbitrarily complex:
a+=a+b*c
⇒ 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.
Modified: 2016-07-03T16:48 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |
![]() |