Section 13.5 Increment / Decrement Operators
Certain incremental and decrement statements, such as the following, are so commonly used in C, especially when working with loops, that there is even a shorthand for the shorthand!
i += 1;
i -= 1;
Because of their ubiquitousness, there is yet another shorthand notation just for these operations of adding one to or subtracting one from a variable!
Investigate 13.4 .
Do you remember what the following is shorthand notation for:
i += 1;
In the following video, we’ll take a look at the shorthand notation that shortens the already short compound assignment operators
+=
and
+=
:
If you cannot see this codecast, please click here .
Video Description.
Shorthand notation for incrementing and decrementing the same variable
i.e. i++;
, ++i
i.e. i--;
, --i
Pre- and post-fix notation: the location of ++
or --
either before or after the variable to be modified determines the timing of the update relative to other instructions that are part of the same statement.
NEW SYNTAX: i++
, for example, is equivalent to i = i + 1
Check Your Understanding Check Your Understanding
1.
What does the following code print to the screen?
int i = 5;
i++;
printf("%d ", i);
printf("%d ", i++);
printf("%d ", i--);
printf("%d ", --i);
Correct
Not quite. Try again!
Not quite. Try again!
Not quite. Try again!
Not quite. Try again!