[Cs3] Question about static variables and cout

Mikhail Nesterenko mikhail at cs.kent.edu
Thu Feb 7 17:20:01 EST 2019


> Here's the code that outputs 21 instead in visual studio instead of 12 like
> it should. I attached the file just in case too.
> 
> #include <iostream>
> 
> using std::endl; using std::cout; using std::cin;
> 
> 
> int myFunc() {
>     static int a = 0;
>     return ++a;
> }
> 
> void main() {
> 
>     cout << myFunc() << myFunc() << endl;  // why does this print 21instead of 12?
>     //vs.
>     cout << myFunc();
>     cout << myFunc();
> 
>     }

BTW, it does so only in Visual Studio. It prints 12 in code produced
by clang.

The reason is that the order of evaluating arguments to extraction
operator is not specified by the standard and can happen in any order.

Here is a more detailed explanation.

   https://stackoverflow.com/questions/11354871/c-input-and-output-stream-operators-associativity

Thanks,
--
Mikhail


More information about the cs3 mailing list