CS156

CS156: Intro to C, Part I

Spring 2018

Increment

See this page as a slide show

CS156 Increment

Shortcut Operators

It’s tedious to say big_ugly_variable = big_ugly_variable + 1, so we have a better way to do that sort of thing:

The expressions can be arbitrarily complex:

Increment and Decrement Operators

Adding or subtracting one (incrementing/decrementing) is so common, that we have special notations for just that:

  • ++ : Increment a variable
  • -- : Decrement a variable

Pre- and Post- Increment

Increment example

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.

Side Effects in C

i = i++;
i++ * i++;
i = --i - i--;
i++;
j = i++;
for (i=0; i<5; i++)

Unpredictable, really!

Modified: 2017-12-19T10:00

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building