Sunday, 15 January 2012

c++ - operator<< chaining and function call order -



c++ - operator<< chaining and function call order -

i have function centered(int a, ostream& os), copyfmt(os) output a temporary stringstream.

i phone call way:

std::cout << std::hex << centered(a,cout) << std::dec;

but output still appears decimal. otoh, if alter to

std::cout << std::hex; std::cout << centered(a,cout) << std::dec;

i right hexadecimal output.

it seems centered() called before operator<<() gets call. why so? specified in standard, gets called first here, or undefined behavior?

operator<< associates left-to-right, means first statement

std::cout << std::hex << centered(a,cout) << std::dec;

is equivalent

operator<<( operator<<( operator<<( std::cout, std::hex ), centered(a, cout) ), std::dec );

with syntax, appears operator<<(std::cout, std::hex) , centered(a, cout) both parameters operator<<. hence, per standard, order unspecified: it's not undefined behavior, compiler free take order prefers.

c++

No comments:

Post a Comment