1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - About Expressions and Statements

By David Bolton, About.com

6 of 8

Avoid Mixing Different Types

This is an old trick from C.
int b=0;
for (int i=0;i<10;i++)
{
    if (b)
        cout << "true" << endl;
    else
       cout << "false" << endl;
    b=1-b;
}
Which works in C++. b=1-b just toggles a true/false flag. Using a bool would be easier to understand.

What does this example program output?

//
#include <iostream>

using namespace std;

int first(int & value)
{
  value = 10;
  cout << "First" << endl;
  return value;
}

int second(int & value)
{
  cout << "Second" << endl;
  return value;
}

int main()
{
  int value = 20;
  cout << (first(value) / second(value)) << '\n';

  return 0;

}
With the compilers I've tried (both from Microsoft) the output has been this:
First
Second
1
But it is not guaranteed as the order of evaluation is indeterminate. One compiler might order and evaluate the expression this way. Another might evaluate both functions in the reverse order.

These functions have side-effects; they modify the passed in parameter so the results are affected by the order. Even changing a compiler's optimize setting might alter the order of evaluation and thus the result. Be on the look out for side-effects and try to avoid them.

On the next page : Operator Precedence in C++

6 of 8

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Avoid Mixing Different Types

©2008 About.com, a part of The New York Times Company.

All rights reserved.