I'm writing some C++ codes for fun and practice, to learn more about language features. I want to know more about static variables and their behaviour in recursive functions. Trying this code in g++ compiler, I'm given expected result:
#include <iostream>
using namespace std;
int f(const int& value)
{
static int result = 0;
return result += value;
}
int main()
{
cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10)));
return 0;
}
But my friend tested same code in Microsoft Visual C++ 6. output is 50, 80, 90
I tested it with other C++ compilers (g++, Borland, Code::blocks and MingW under Linux, Win and Mac) output was 110, 100, 40
. I can't understand how output could be 50, 80, 90
...
Why MSVC's output is different?
The order of evaluation of the following three subexpressions is unspecified:
f(10)
f(f(10))
f(f(f(10)))
The compiler may evaluate those subexpressions in any order. You should not rely on a particular order of evaluation in your program, especially if you intend to compile using multiple compilers.
This is because there is no sequence point anywhere in that expression. The only requirement is that each of those subexpressions is evaluated before the result is needed (that is, before the result is to be printed).
In your example, there are actually several subexpressions, which I've labelled as a through k here:
// a b c d e f g h i j k
cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10)));
The calls to operator<<
(a
, c
, d
, g
, and h
) all have to be evaluated in order because each depends on the result of the previous call. Likewise, b
has to be evaluated before a
can be evaluated, and k
has to be evaluated before j
, i
, or h
can be evaluated.
However, there are no dependencies between some of these subexpressions: the result of b
is not dependent upon the result of k
, so the compiler is free to generate code that evaluates k
then b
or b
then k
.
For more information on sequence points and related unspecified and undefined behavior, consider reading the Stack Overflow C++ FAQ article, "Undefined Behavior and Sequence Points" (your program doesn't have any undefined behavior, but much of the article still applies).