# Shortcut Operators

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

# 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
• The operators can be placed before, ++i, or after, i++, the variable. These two expressions have different behaviors.

# Pre- and Post- Increment

• Pre-incrementing, ++i, causes the variable to be incremented before it is used in the expression that contains it.
• Post-incrementing, i++, causes the variable to be incremented after it is used in its containing expression.
• Depending on context, you may see the same or different behaviors from these two expressions.

# 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

• The use of the increment and decrement operators in expressions can result in undefined (unpredictable) behavior, because post-increment and post-decrement take place sometime after the value is returned.
• Stick to using these operators as the only part of an expression.
• Don’t do things like this:

i = i++;
i++ * i++;
i = --i - i--;
• These are okay:

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

# Unpredictable, really!

• I'm serious about this—statements like i = i++;, or using an uninitialized variable, are undefined behavior.
• Showing me that it works won’t impress me, either.
• Yes, it happens to produce the result that you want on that computer, with the current version of that particular compiler.
• That doesn’t mean that it’ll work on the GTA’s computer, with a different compiler.
• I want you to write code that works everywhere, always.

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