c++ function call within cout statement [duplicate] - c++

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.

Related

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.

C++ cout behavior / order of execution

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.

What is the compiler doing with parameters vs without parameters? [duplicate]

This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 4 years ago.
I have a non important question about compilers for C++. The following code outputs
1
2
3
and I can't figure out why. What difference does declaring it with empty parameters make to no parenthesis at all?
#include <iostream>
using namespace std;
int main()
{
int x;
cout << x << endl;
int y();
cout << y << endl;
int z(2);
cout << z << endl;
return 0;
}
The compiler is g++.
The 1st one, x is default initialized with indeterminate value, then cout << x leads to undefined behavior, means anything is possible.
Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values
The 2nd one, int y(); declares a function named y, which has no argument and returns int. For cout << y, y will decay to function pointer, which could convert to bool implicitly and then you'll get 1 (i.e. true. You can use std::boolalpha like std::cout << std::boolalpha << y to get the output true).
The 3rd one, z is direct initialized with value 2, then cout << z you'll get 2.
LIVE sample with clang, note all the warning messages the compiler gives.

Keep track of how many times a recursive function has been called in C++

I am trying to work on a program that has a function whose parameter is an vector of string. I want to use recursive on that function but everytime the function is called, I want to change the parameter to say for example
fun(stringArray[i])
where i is the number of time the function has been called.
So in simpler way something like following. But I need to keep track of how many times the function fun has been executed.
void fun(){
cout<<hi;
if(x!=10)
fun()
}
int main(){
fun();
}
In this one let's say I want to print it out just 10 times, so want to have a varible that increments, and when reaches 10, it stops. So in general what can I do to keep track of it? I tried using global variables but they don't seem to work with functions. Any suggestions?
I've seen quite a mess here so I decided to clear the things out.
Solution 0: Static Variable
Consider the code proposed with a small modification
#include<iostream>
using namespace std;
void fun()
{
static int count=1;
count++;
cout << "fun() is called " << count << " times" << endl;
if(count<=10)
{
fun();
}
}
int main()
{
cout << "first call" << endl;
fun();
cout << "second call" << endl;
fun();
cout << "third call" << endl;
fun();
}
resulting in this output:
first call
fun() is called 2 times
fun() is called 3 times
fun() is called 4 times
fun() is called 5 times
fun() is called 6 times
fun() is called 7 times
fun() is called 8 times
fun() is called 9 times
fun() is called 10 times
fun() is called 11 times
second call
fun() is called 12 times
third call
fun() is called 13 times
As you can see, using static variables could lead to some unexpected behaviour.
This is a one shot function that will cause you quite some headaches in the future.
Furthermore, the usage of static variables leads to an unreadable code that is error prone
Just don't do it!
Solution 1: Variable passed by value
Consider this code:
#include <iostream>
using namespace std;
void fun(int i){
cout<<i<<endl;
if(i!=3) {
i++;
fun(i);
fun(i);
}
}
int main(){
fun(0);
}
This is the output:
0
1
2
3
3
2
3
3
1
2
3
3
2
3
3
As you can see the output is not the number of times the function is called
Solution 2: Variable passed by reference
#include <iostream>
using namespace std;
void fun(int& x){
if(x>=10)
return;
++x;
cout << x << endl;
fun(x);
}
void funEntry(){
int x = 0;
cout << "Entry point" << endl;
fun(x);
}
int main(){
funEntry();
funEntry();
}
will print
Entry point
1
2
3
4
5
6
7
8
9
10
This approach will work also with some more exotic recursive pattern like this one
#include <iostream>
using namespace std;
void fun(int i, int& x){
if(i>=4)
return;
++x;
cout << i << " " << x << endl;
fun(i+1,x);
fun(i+2,x);
}
void funEntry(){
int x = 0;
cout << "Entry point" << endl;
fun(0,x);
}
int main(){
funEntry();
funEntry();
}
Output:
Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7
Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7
Add a static variable as counter.
#include<iostream>
using namespace std;
void fun()
{
static int count=1;
count++;
cout << "fun() is called " << count << " times" << endl;
if(count<=10)
{
fun();
}
}
int main()
{
fun();
}
static variables are initialized only once and the value will be retained across function calls. See this link http://en.wikipedia.org/wiki/Static_variable
void fun(int& x){
if(x>=10)
return;
... Do something
++x;
fun(x);
}
You should use a reference to an external variable
If you pass the counter by value you can't make multiple calls in the same function
use static variable inside the recursive function.
static int i =0;
and in the beginning of the function, say i++.
every time the function is called, this i will be incremented. and if the value of i become 10, you can terminate.
if you need to make it recursive...
void fun(int i){
cout<<hi;
if(i!=10) {
i++;
fun(i);
}
}
int main(){
fun(0);
}
Hope that helps?
I know I am really late to answer this question. But anyway, the approach, followed by me involves pointers concept in #1, and pass by reference concept in #2. I have tested this solution for Towers of Hanoi problem, and it will work nearly for all kind of recursive functions in my opinion.
Actually, code written in first approach is originally in C, but it will work in C++ too, for obvious reasons.
Approach #1: Using pointers in C.
Lets say we denote the recursive function by rf()
An integer variable, lets say, with name invocations has to be created, to be passed to the recursive function along with other arguments (if present). It must be created in main() or the calling function. Initialize it to 0.
Then, in the recursive function parameter list, add another parameter with type integer pointer, and in the calling function, pass to recursive function, the value of this parameter as the address of the variable invocations defined in this calling function.
e.g.
void main(){
int invocations=0;
rf(n,&invocations); // address of variable 'invocations' is passed here
}
Then, in the declaration part of recursive function, where you have added an extra parameter for counting function invocations, and declared its type as int pointer,
in the first line of function body itself, increment the value pointed by this integer pointer by 1 in the following way,
void rf(int n, int* invocations){
(*invocations)++;
/* rest of the function logic goes here */
}
Notice here that I have put the de-referencing operator (*), asterisk, inside parentheses in order to tell compiler to evaluate it first, as if I don't do that, the increment operator on its right will be evaluated first in absence of the parentheses (since * and ++ have same precedence, and if present in the same expression, they will be evaluated from right to left)
Next, print the value of invocation variable, after all the recursive function calls are over in the calling function, here in our case, inside main().
Like this,
void main(){
......
int invocations=0;
.......
rf(n, &invocations);
printf("\nNumber of invocations of rf()=%d\n", invocations);
}
Approach #2 : Using pass by reference in C++
All the above steps are same, only changes involved are in following ways,
Change the parameter type in rf() declaration from int* to int&. Like
void rf(int n, int* invocations) to void rf(int n, int& invocations)
Change the rf() call statement, pass the variable value, not its address.(remove simply the &), like rf(n, &invocations); to rf(n, invocations);
Change the incrementation statement of invocations variable from (*invocations)++; to simply invocations++ inside rf() body.
That's all. Both the solutions will produce same effect. Both of them works in my case.
Tell me if the solution is unclear at any step or if it fails to work in your case.

Doubt related '&' operator in Function definition! [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Pointer vs. Reference
Hi All,
I was trying to explore and I encountered a concern with the reference operator. Consider a normal call by reference swap code as below, which works as desired
#include<iostream>
using namespace std;
void test(int *a,int *b){
int temp;
temp = *a;
*a= *b;
*b= temp;
cout<<"\n Func a="<<*a << " b=" << *b;
}
int main()
{
int a=5,b =3;
cout<<"\n Main a="<<a << " b=" << b;
test(&a,&b);
cout<<"\n Main again a="<<a << " b=" << b;
return 0;
}
On the other hand a code as below also does the same kind of swapping and yield exactly the same result.
#include<iostream>
using namespace std;
void test(int &a,int &b){
int temp;
temp = a;
a= b;
b= temp;
cout<<"\n Func a="<<a << " b=" << b;
}
int main()
{
int a=5,b =3;
cout<<"\n Main a="<<a << " b=" << b;
test(a,b);
cout<<"\n Main again a="<<a << " b=" << b;
return 0;
}
Can some one explain how different is the function call in the second example(first part I am comfortable in which the address is taken as the reference, but what happens in the second case) ?
Within the same line, hope the same happens in an assignment statement as well i.e.
int a=5;
int &b=a;
Thanks in advance.
EDIT:
Thanks for the replies. But my doubt is what exactly happens in the memory
int *pointer=&x
stores the address but what happens when we do
int &point=x.
Both versions perform an identical job and quite probably the compiler will emit identical object code.
The version using reference parameters is much easier to read.
You can pass a NULL pointer to the version that uses pointers which leads to a memory violation. The same mistake cannot be made with reference parameters.
& means that you're passing your parameter by reference. The variable you've passed is exactly the same variable you're operating in your function. Actually there is no significant difference between using pointer or reference, because when you passing pointer and then dereference it, you again get exactly the same variable. To sum up: in both cases it's possible to modify passed variable. The opposite, when you pass variables value.
In both cases you are passing the variables by reference. In the first function you can conceptually think of the address that is being passed. In the second example though, I conceptually think of the variable itself being passed, but passed by reference instead of by value.
I am not 100% sure, but I suspect on most compilers they would compile to the same object code.