Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Local Static variables and cout

Status
Not open for further replies.

tavianator

Programmer
Nov 5, 2006
2
0
0
CA
could someone please explain to me why this code produces

1: 3
2: 2
3: 1

as-is, and

1: 1
2: 2
3: 3

when uncommented?

Code:
int foo()
{
	static int i = 0;
	return ++i;
}

int main(int argc, char* argv[])
{
	std::cout     << "1: " << foo() << std::endl//;
	/*std::cout*/ << "2: " << foo() << std::endl//;
	/*std::cout*/ << "3: " << foo() << std::endl;
	return 0;
}
 
Apparently the order of execution is right to left, so the 3rd foo() gets run first...
I wouldn't always count of that being the case though. Different compilers might execute statements from left to right.
 
ok, it just seems wierd that the operator is evaluated left-to-right, but the functions aren't evaluated in that order.
 
You can see what it's doing a little better like this:
Code:
#include <iostream>

int foo( char c )
{
    static int i = 0;
	std::cout << c << std::endl;
    return ++i;
}

int main(int argc, char* argv[])
{
    std::cout     << "1: " << foo( 'a' ) << std::endl//;
    /*std::cout*/ << "2: " << foo( 'b' ) << std::endl//;
    /*std::cout*/ << "3: " << foo( 'c' ) << std::endl;
    return 0;
}

I get the following output:
c
b
a
1: 3
2: 2
3: 1


If you put a breakpoint on the cout line in main(), then step into each function call, you can see it execute the foo()'s from right to left, then the << insertions from left to right.
It's weird, but that's what happens when you try to combine too many things into a single line in C/C++. ;-)
 
> could someone please explain to me why this code produces
Because the first version invokes undefined behaviour.

Getting 3 2 1 is just as likely as getting 1 2 3 or indeed other possible answers (as befits undefined behaviour).

Since your original code does [tt]++i[/tt] three times between sequence points, the result seems at odds with expectation.

> It's weird, but that's what happens when you try to combine too many things into a single line
It's only weird when the thing in question has multiple side effects on the same object.

> it just seems wierd that the operator is evaluated left-to-right, but the functions aren't evaluated in that order.
Given [tt]f1() + f2()[/tt], there is nothing in the standard which says which should be called first.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top