C++ cout behavior / order of execution - c++

I was looking at some example questions of CPPInstitute's CPA-21-01 exam, and am a bit confused about Question #11.
It states the following:
What is the output of the following program?
#include <iostream>
using namespace std;
class A {
public:
A() {
a.a = a.b = 1;
}
struct { int a,b; } a;
int b(void);
};
int A::b(void)
{
int x=a.a;
a.a=a.b;
a.b=x;
return x;
}
int main(void) {
A a;
a.a.a = 0;
a.b();
cout << a.b() << a.a.b << endl;
return 0;
}
A. The program will cause a compilation error
B. 10
C. 01
D. 11
It can be boiled down a more minimal example:
int swap_and_return(int& a, int& b) {
std::swap(a,b);
return a;
}
int main() {
int a = 0;
int b = 1;
cout << swap_and_return(a,b) << a << endl;
return 0;
}
So far so good; The answer key says it's B.
Let's say you choose D.
According to this, the execution order is arbitrary:
15) In a function call, value computations and side effects of the initialization of every parameter are indeterminately sequenced with respect to value computations and side effects of any other parameter.
There has already been a similar question here
I think the cout line can be translated into cout.operator<<(a.b()).operator<<(a.a.b);, meaning there should be a sequence point and behavior should be deterministic?
In practice, the following results are obtained:
MS cl.exe, Debug: 10
MS cl.exe, Release: 11
GCC, C++11: 11
Clang: 11
Needless to say, I am a bit confused now, because they say it's answer B when it appears that indeed order of execution is arbitrary.
Could anyone please explain whether I am right about the execution order and what it should be then?
Thanks!

Before C++17, you're right, and the quiz does not allow for the right answer.
Since then, the answer is deterministic.

Related

Are function arguments not evaluated left to right? How are side effects on the same variable ordered?

Consider the following program.
#include<iostream>
using namespace std;
void fn(int a, int b)
{
cout << a;
cout << b;
}
int main()
{
int a = 10;
fn(a++, --a);
fn(a--, ++a);
return 0;
}
I don't understand the output I get (gcc 11.2):
9101110
Shouldn't a++ be evaluated first? How can fn then get a 9? Is this undefined behavior or simply "indeterminate"? Did C++17 change in this respect?
This is undefined behavior. The order of parameter evaluation is unspecified.
See here.
So this question is irrelevant and code like this should never be used.
The output can be 9 10 11 10 on one compiler, and a totally different value on another compiler (while both compilers remain standard-complaint).

The address always returned is 0 instead of the actual value

Here is the simple code:
int *ad_return()
{
int a=600;
cout << &a << endl;
return &a;
}
int main()
{
cout << ad_return();
return 0;
}
The output is unexpected. The first cout prints an address that looks like a address but the cout that is in the main prints a legit 0. I couldn't find an explanation anywhere.
Based on what I have experimented, I have concluded the following:
Since the address of a local variable that has already went out of scope is undefined, it seems that gcc and g++ decided to implement a feature that sets this to zero (probably to make sure that the code segfaults instead of generating thoroughly bizarre behaviour). It does not do this in clang, but the value is undefined so both of these compilers are operating in accordance with the standard.
Try This Code.
There was problem you were trying to access address of a local variable a it is not accessible out side of the function as_return(). So declare it in global so that it is accessible to everyone.
#include<iostream>
using namespace std;
int a;
int *ad_return()
{
a=600;
cout << &a << endl;
return &a;
}
int main()
{
cout << ad_return();
return 0;
}
.
I hope you got answer

Member call over operator<<

Here is my problem:
int addsomeStuff(std::ostream &cout, int b) {
cout << b;
return 2;
}
int main() {
int a = 1;
cout << a << addsomeStuff(cout, 3) << endl;
return 0;
}
Output: 312
Can Someone explain me the Output, i would expect the output more like 132
why is the compiler runs first the Function before making the operator.
How i run into this issue:
I have a container class which can hold data inside an bytearray.
Somehow the 'container.WriteConvert(..);' get inserted into bytearray before the integer called 'a'. Does anyone have an explaintation for that.
I could make the WriteConvert static or add an extra Line which would fix this problem, instead of returning an Container& but i am kinda intrested whats the reason the Compiler puts this in this order.
int a = 2;
Container container;
container << a << container.WriteConvert("TestString");
int b = 0;
container >> b;
cout << b;
// The ouput of 'b' is some stupid Data which is caused by WriteConvert.
The Reason i didnt wrote this WriteConvert static or outside of the Container class has some reason. I have also ReadConvert which i dont want to have multiline. If someone has another idea i am open for other solutions, without increasing line amount.
int b = 0;
string output
container >> b >> container.ReadConvert(output);
cout << b;
Pre C++17, the order of evaluation of the chained operator arguments' was unspecified. That means the execution could've first evaluated addsomeStuff(cout, 3) call (thus printing 3 first) and then proceed to print a and the returned value of addsomeStuff(cout, 3).
With C++17, the order of evaluation is well defined - left to right. That means that if your compiler correctly implements the C++17 standard, the only possible output is 132.
If you are stuck with a pre C++17 standard, you would need to first evaluate all the arguments and then use them in chained operator call or don't use chained operator calls:
int main() {
int a = 1;
cout << a;
cout << addsomeStuff(cout, 3) << endl;
return 0;
}
The former approach may alter the behaviour, but will be well-defined.

Why does the value change based on whether or not I print a value in the constructor?

Given the following C++ code segment, the behavior and output is as expected:
#include <iostream>
using namespace std;
class A {
public:
int n;
int *p;
A(int n);
};
A::A(int n) {
this->n = n;
this->p = &n;
cout << *(this->p) << endl;
}
int main(int argc, char *argv[]) {
A a(55);
cout << a.n << endl;
cout << *(a.p) << endl;
}
The output is:
55
55
55
But when the print line in the constructor is commented out, this is the result:
#include <iostream>
using namespace std;
class A {
public:
int n;
int *p;
A(int n);
};
A::A(int n) {
this->n = n;
this->p = &n;
// cout << *(this->p) << endl;
}
int main(int argc, char *argv[]) {
A a(55);
cout << a.n << endl;
cout << *(a.p) << endl;
}
Output:
55
32767
I realize that 32767 is not an arbitary number, as it is (2^15)-1, but why does the value printed by the final cout statement of the main method change based on whether that line in the constructed is commented out or not?
this->p = &n;
n here resolves to the parameter to the constructor. This sets p to point to the argument to the constructor, and not the class member. When the constructor terminates, p points to a destroyed object (the constructor parameter value), and dereferencing p is undefined behavior.
This is one argument against using the same names for the constructor's parameters as the names of class members that are getting initialized. Makes it easy to unintentionally create undefined behavior.
Change this to:
this->p = &this->n;
to get the expected results.
This line:
this->p = &n;
means "set this->p to point at the local variable n". Which is perfectly fine, except that the local variable goes out of scope immediately afterward, after which point any attempt to dereference p invokes "undefined behavior" (because it points to memory that is no longer properly allocated). This means that the program is allowed to do absolutely anything, up to and including growing a fist and shaking it at you menacingly. (Fortunately, no major compilers support that kind of biotechnology yet.)
If you run the same experiment on a different compiler, you will likely see a different result, as it's quite random.
I'm guessing that you instead meant to write
this->p = &(this->n);
so that it instead points to the member n?

c++ function call within cout statement [duplicate]

This question already has answers here:
Order of evaluation of arguments using std::cout
(5 answers)
Closed 1 year ago.
I'm learning c++, and recently run into a confusing problem, here's the code:
#include <iostream>
using namespace std;
class A {
public:
A() { a[0] = 1; a[1] = 0; }
int a[2];
int b(void) { int x=a[0];a[0]=a[1];a[1]=x; return x; }
};
int main(void) {
A a;
cout<<a.a[0]<<a.a[1]<<endl; //outputs 10
a.b();
cout<<a.a[0]<<a.a[1]<<endl; //outputs 01
a.b();
cout<<a.a[0]<<a.a[1]<<endl; //outputs 10
cout << a.b() << //outputs 1
endl<< a.a[0]<<a.a[1] << endl; //outputs 10???
cout<<a.a[0]<<a.a[1]<<endl; //outputs 01???
return 0;
}
The first two calls of b() behaves as expected, but when i call b() within the cout statement, it doesn't switch the two elements of the array right away, but later i check it, it's already switched.
Can you help me understand this behavior? Thank you.
std::cout << f() << g();
The order of evaluation of the two function calls is unspecified; the compiler can call g() then f(), or it can call f() then g().
Same thing in your code; the compiler can squirrel away the value of a.a[0] the call a.b(), or it can call a.b() then grab the value of a.a[0].
Function evaluation in an expression depends on compiler stream operations such as << and >>. The same problem that happens when you evaluate x = f1() + f2(). You don't know which will be evaluated first because it's compiler dependent.
It would be more safe to call these on separate lines to rule out the ambiguity.