   Weirdness surrounding cout
  Hi, i''ve discovered some pretty bizzare behaivor in cout. If I have a function like so...   int i=0;char RetChar(){   char array[] = {''a'', ''b'', ''c''};   if (i == 4)   { i = 0; return array[i++];   }   else return array[i++];}main....{   cout << RetChar;   cout << RetChar << endl; // output ab   i=0;   cout << RetChar() << RetChar() << endl; //output ba<-?!?!?}Why does this happen? I would think cout <<""; cout <<""; = cout << "" cout <<""; Damn library. Oh well, luckily console isn''t my target platforms. Though I am curious to why this works like it does. Thank you advance for answering my question 
  cout isn''t the problem here, the language is.The C++ language specification doesn''t define the order in which function arguments are evaluated, except in the case of certain sequence control points (like the comma operator).What is probably happening is this:RetChar() is manipulating a global variable i. The *compiler* is probably evaluting the RetChar function calls on the line:cout << RetChar() << RetChar() << endl;from right to left and storing their return values in temporaries (Visual Studio is fond of right-to-left evaluation in situations like these, but you''d have to look at the generated assembly to verify this, and YMMV in that respect).The temporaries would be sent to the operator<<() function in the proper order (e.g., as you expect cout << A << B << C will always print A B C in that order), but since the rightmost call to RetChar is being evaluated first, it returns ''a'' and then the second call returns ''b''.This illustrates one of the reasons one needs to be careful with global variables.;  might be a good idea with if(i == 3) instead, since you only have 3 entries in your array ;  (not really, he is using postfix increment, thus element 3 is outputted when i is incremented to 4) ;quote:Original post by marijnh  (not really, he is using postfix increment, thus element 3 is outputted when i is incremented to 4)   yes, but there is no "element 3", only 0-2.small thing on the side: avoid redundant code like this:if (i == 4){ i = 0; return array[i++];}else return array[i++];the not so tragic part: the longer your if-block, the bigger the jump it has to perform the more likely missing the cache (speed). also: whenever you have something that appears in all branches it obviously shouldnt be in a branch (readability).if (i == 3) i = 0;return array[i++]; 