CS253: Software Development with C++

Spring 2018

Increment

See this page as a slide show

CS253 Increment

Pre-/Post-Increment/Decrement

This example is bad. Don’t do this:

int n = 1;
cout << ++n * ++n << endl;
c.cc: In function 'int main()':
c.cc:2:9: warning: operation on 'n' may be undefined
9

Another bad example

Don’t do this, either:

short nums[] = {1, 2, 3, 4};

short *p = nums;
cout << *p++ << ' ';
cout << *p++ << '\n';

p = nums;
cout << *p++ << ' ' << *p++ << '\n';
c.cc: In function 'int main()':
c.cc:8:26: warning: operation on 'p' may be undefined
1 2
2 1

Why not?

Why not? Because, in both cases, the variable is being modified twice in the same expression.

Another Example

int a() { cout << 'A'; return 1; }
int b() { cout << 'B'; return 2; }

int main() {
    cout << a()+b() << '\n';    // Might print AB or maybe BA.
    cout << a() << b() << '\n'; // Might print A1B2, AB12, BA12
    return 0;
}
AB3
BA12

Experiments don’t matter

You cannot determine the “correct” result by experimentation.

How to do it right

Break apart expressions, perhaps using explicit temporaries, to determine the order of evaluation of sub-expressions:

int a() { cout << 'A'; return 1; }
int b() { cout << 'B'; return 2; }

int main() {
    int c = a();        // Will print A
    c += b();           // Will print B
    cout << a();        // Will print A1
    cout << b();        // Will print B2
    return 0;
}
ABA1B2

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:53

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