CS253

This file defines the header for each page. An optional "icon" image (I use the textbook):

Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2014

Example Increment

Links to the various pages for this class:

Wish I could do this: * Schedule

Post-Increment

This example is bad. Don’t do this:

#include <iostream>
using namespace std;

int main() {
   int n = 1;
   cout << ++n * ++n << endl;
}

Don’t do this, either:

#include <iostream>
using namespace std;

int main() {
   short nums[] = {1, 2, 3, 4};

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

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

Why not? Because, in both cases, the variable is being modified twice in the same expression. cout << a << b is one expression. << is an operator, just like + is. C++ does not determine the order of execution of the various parts of the expression, except for a few special cases.

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

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

You cannot determine the “correct” result by experimentation.

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
    }

Modified: 2014-02-02T23:13

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