Code:int print(void); int main(void) { cout << "The Lucky " << print() << endl; //This line return 0; } int print(void) { cout << "No : "; return 3; }
expected output is THE LUCKY 3
but what i got is NO: THE LUCKY 3
please help me.Thank you
Code:int print(void); int main(void) { cout << "The Lucky " << print() << endl; //This line return 0; } int print(void) { cout << "No : "; return 3; }
expected output is THE LUCKY 3
but what i got is NO: THE LUCKY 3
please help me.Thank you
The order of evaluation is unspecified, hence it is possible for "The Lucky" to be printed before or after print() is called. To fix this, break the chain:
This should do what you want, but I am still uncomfortable with it. Why does it return 3? Why not just write:Code:cout << "The Lucky "; cout << print() << endl;
Then call it as:Code:void print() { cout << "No : 3"; }
? Or you could simply not have this print function, but I presume you simplified your example from something less trivial.Code:print();
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
what is mean the order of evaluation.detial please
There can be no detail about the order of evaluation, because the order of evaluation is not specified. As long as all the things that are supposed to happen do happen, they can happen in whatever order the compiler finds convenient. (The only thing that must happen is that the 3 must be somewhere after the "no:", but it need not be immediately after.)
I'll go with the simplest:
Code:#include <iostream> int myprint() { return 3; // return this to the stream } int main() { std::cout // opens the stream << "Lucky number: " // print some nice text << myprint() // print the returning value << std::endl; // line jump return 0; }
* PC: Intel Core 2 DUO E6550 @ 2.33 GHz with 2 GB RAM: Archlinux-i686 with xfce4.
* Laptop: Intel Core 2 DUO T6600 @ 2.20 GHz with 4 GB RAM: Archlinux-x86-64 with xfce4.
If you look at this statement:
int x = a() + b() + c();
You cannot tell which of the function a, b and c the compiler will invoke in what order. You probably assume that the functions will be called like
a
b
c
But in reality, the compiler is allowed to call them in any order, so
c
b
a
or even
c
a
b
is allowed. This is called the order of evaluation.
Because of this, it is either recommended that you
Call the function sequentially and cache their return values and then do stuff with them, or
Make sure the functions have no side effects (that means they must only return a value and may read variables, but may never write to any variables but local variables).
Code:int foo(int& x) { std::cout << "Meh."; // <--- This has side effects since std::cout is a global object which you are writing to. x = 10; // <--- This has side effects since you are writing to a non-local variable. int y = 10; y = 20; // <--- OK, writing to a local variable return y; // <--- OK, returning a local variable }