This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: The order of calling functions and << <<



> The following compiler behaviour is different from gcc-2.7 if I remember well.

> #include <iostream>
> 
> int foo(void)
> {
>   cout << "2";
>   return 3;
> }
> 
> int main(void)
> {
>   cout << "1" << foo() << "4" << endl;
>   return 0;
> }

> ...  What does the ANSI/ISO C++ standard say about this?

The standard says that the behavior of the above program is undefined,
because the order of evaluation of arguments to a function call is unspecified.

You have written

operator<<(operator<<(operator<<(operator<<(cout, "1"),foo()),"4"),endl);

The source of the undefined behavior is that in

operator<<(operator<<(cout, "1"), foo());

the compiler is free to either do operator<<(cout,"1") first or to call
foo() first.  This means that you could get "124\n" or "214\n".



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]