Bug 9334

Summary: args to cout evaluated prematurely
Product: gcc Reporter: bala
Component: c++Assignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: normal CC: gcc-bugs
Priority: P3    
Version: 2.95.3   
Target Milestone: ---   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed:
Attachments: linuxcout.e

Description bala 2003-01-15 12:46:03 UTC
a cout statement in is causing the gcc version 2.95.3 20010315 (SuSE) in Linux to prematurely pass the value of an int variable before any preceeding operator<< is evaluated on the cout.

(See "How-To-Repeat:" for the program)
// LINUX
monsterd01:~/c++> uname -a
Linux monsterd01 2.4.18-3-rmap12h-lvm105 #1 SMP Wed Aug 7 17:54:19 EDT 2002 i686 unknown
monsterd01:~/c++> /usr/bin/g++ -v
Reading specs from /usr/lib/gcc-lib/i486-suse-linux/2.95.3/specs
gcc version 2.95.3 20010315 (SuSE)
monsterd01:~/c++> /usr/bin/g++ linuxcout.C
monsterd01:~/c++> a.out
foo(&x): 100, x: 1111

//SUN
booby:~/c++> uname -a
SunOS booby 5.8 Generic_108528-16 sun4u sparc SUNW,Sun-Blade-100
booby:~/c++> g++ -v
Reading specs from /usr/local/gnu/install/gcc/2.9.5.2/lib/gcc-lib/sparc-sun-solaris2.6/2.95.2/specs
gcc version 2.95.2 19991024 (release)
booby:~/c++> g++ linuxcout.C 
booby:~/c++> a.out
foo(&x): 100, x: 100

Release:
2.95.3

Environment:
LINUX:
monsterd01:~/c++> uname -a
Linux monsterd01 2.4.18-3-rmap12h-lvm105 #1 SMP Wed Aug 7 17:54:19 EDT 2002 i686 unknown
monsterd01:~/c++> /usr/bin/g++ -v
Reading specs from /usr/lib/gcc-lib/i486-suse-linux/2.95.3/specs
gcc version 2.95.3 20010315 (SuSE)

How-To-Repeat:
#include <iostream>
int foo(int* changeme) { return (*changeme = 100); }
int main() {
  int x=1111;
  std::cout << "foo(&x): " << foo(&x) << ", x: " << x << std::endl;
}
// BTW: there was no complaint when I used an unqualified endl instead of std::endl;
Comment 1 bala 2003-01-15 12:46:03 UTC
Fix:
Split the cout stmt above into two statements--one where x is evaluated and then one where x is printed:

std::cout << "foo(&x): " << foo(&x);
std::cout << ", x: " << x << std::endl;
Comment 2 Wolfgang Bangerth 2003-01-15 13:46:22 UTC
State-Changed-From-To: open->closed
State-Changed-Why: That's how C++ works: the order of evaluation of statements
    between sequence points is unspecified. So either the
    value of "x" or of "foo(&x)" is pushed on the stack first.
    Most any good C/C++ book will explain the matter.
    W.
Comment 3 Andrew Pinski 2005-04-20 03:02:39 UTC
Reopening to ...
Comment 4 Andrew Pinski 2005-04-20 03:02:59 UTC
Mark as a dup of bug 11751.

*** This bug has been marked as a duplicate of 11751 ***