CS156: Intro to C, Part I

Spring 2018

Increment

See this page as a slide show

CS156 Increment

Shortcut Operators

big_ugly_variable = big_ugly_variable + 1 is tedious. We have a better way:

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!

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-02-25T13:00

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building