evaluation orcer <<

here is a simple test program that demonstrates the evaluation order for operator<< applied to ostreams
#include <iostream>

char nextchar()
{
static int n=97;
n++;
return char(n);
}


void main()

{
std::cout<<nextchar()<<nextchar();

}

This evaluates the second nextchar() before the first and the output is "cb". The question is why?

The binding for operator << is left to right just as the '+' operator. Therefore I'd expect this to evaluate cout.operator<<(nextchar()).operator<<(nextchar()) to produce an output of "bc", but that is definitely not what happens. Stroustrup says in 21.2.2 of The C++ programming language, special or 3rd edition that the compiler would interpret my statement at
operator<<(cout,nextchar()).operator<<(nextchar()) which again seems to me will also produce "bc"
Last edited on
cppnewuser13 wrote:
This evaluates the second nextchar() before the first and the output is "cb". The question is why?

This is what it does on your specific version of your compiler on your platform. Many other compilers print "bc" (I tested a few, after fixing your "void main" error)

Evaluation order in C++ is unspecified (except for a few special sequencing requirements). You're quoting operator precedence/associativity which is not the same thing.

see http://en.cppreference.com/w/cpp/language/eval_order
Last edited on
thank you for your helpful response that I wouldn't have got to on my own.
Topic archived. No new replies allowed.