Jump to content

  • Log In with Google      Sign In   
  • Create Account


A strange issue with the scope of the << operator


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
9 replies to this topic

#1 Shaquil   Members   -  Reputation: 815

Like
0Likes
Like

Posted 10 October 2012 - 06:41 PM

Actually, the title is a bit of a misnomer. I doubt the issue is with the operator itself. More likely it's something I just don't understand. The problem is, vaguely put:

I'm declaring a variable within
int main()
, and then, in one line, altering its value by passing it by reference to a function, then outputting it via
cout <<
. Only problem is,
cout <<
is printing the original initialized value of the variable to the screen, rather than the newly altered version. I have come up with a solution, but I don't like it. Actually, the code is simple enough that I can post it (below). It's a simple Half Adder function. Take two binary inputs, output the result and the carry. I pass the carry by reference, and have the function return the result of the addition.

#include <iostream>
using namespace std;

bool HalfAdder(bool, bool, bool&);

int main(int argc, char ** argv){

bool input[] = {true, true};
bool carry = false;

cout << "Result is " << HalfAdder(input[0], input[1], carry) << " carry is " << carry << endl;
system("PAUSE");

return 0;
}//end of main

bool HalfAdder(bool a, bool b, bool& carry){

if( a & b ){
	   //1 + 1 = 0, carry = 1
	   carry = true;
	   return false;
}//end of if

else{
  //1 + 0 = 1, no carry. No carry with 0 + 0 either
	   carry = false;
   //1 + 0 = 1; 0 + 0 = 0
	   return (a || b) ? true : false;
}//end of else

}//end of HalfAdder()

If you run this, unfortunately, carry is always 0. False. Because it's initialized as false. This, of course, despite the fact that I pass it by reference in the call. While I'm sure the C/C++ veterans have probably already scrolled down to the reply box by now, for those of you still reading, I'd like to offer a theory for some feedback (I'll do the research later tonight). I believe that the problem is that I'm passing HalfAdder as a parameter to the << member function of cout on the same line that I pass carry to another instance of <<.

So while I expected this sort of thing to happen:


cout.operator<<("Result is");
cout.operator<<(HalfAdder());
cout.operator<<("carry is");
cout.operator<<(carry);

What really happened is something like...

cout.operator<<("Result is", HalfAdder(), "carry is", carry);

Not that exactly, but that basic concept. What I mean is, maybe all of the parameters I passed to << were copied immediately, and then HalfAdder() was executed, so that even though carry has been altered, it's too late; the original value of carry was copied already. I tested this out by running the same code but adding an extra line before
system("PAUSE")
.

cout << "Result is " << HalfAdder(input[0], input[1], carry) << " carry is " << carry << endl;
cout << "But the true carry is " << carry << endl;
system("PAUSE");

And, hey, it says the true carry is 1, as expected. That's actually pretty amazing. I never even thought of that. Oddly enough, I compiled this in Dev-C++ before handing it in for class, and I assume it worked fine, otherwise I probably wouldn't have handed it in. Is it even remotely possible this is a compiler-specific thing? My most recent build of it where I noticed the error was in MSVC++2012.

Anyway, thanks for your time. Sorry if this was too much too read. I just think it's a pretty cool error to have made.

Sponsor:

#2 kuramayoko10   Members   -  Reputation: 386

Like
0Likes
Like

Posted 10 October 2012 - 07:04 PM

I've faced this problem before.

I believe that this kind of thing with i/o streams
std::cout << a(&val) << val;

generates an Unspecified Behavior.

The std::cout function will print the arguments in the order you provided, but it cannot guarantee that they will be executed from lef-to-right or right-to-left.
I think that the compiler is the one that is translating this to a random order of execution. DevC++ (gcc?) did it left-to-right as you expected but the vc++ from Visual Studio did it differently.

Anyhow, I think it is better to break this line into two as you have shown above.

Edited by kuramayoko10, 10 October 2012 - 07:05 PM.

Programming is an art. Game programming is a masterpiece!

#3 fastcall22   Crossbones+   -  Reputation: 4019

Like
1Likes
Like

Posted 10 October 2012 - 07:05 PM

The problem stems from the order in which arguments are evaluated. It's possible that (a copy of?) carry is evaluated first, before HalfAdder is called. It's also possible that the behavior of the statement is undefined, meaning that you may get different behavior depending on the compiler. For the sake of clarity and readability, I would suggest evaluating HalfAdder separately before writing the result:
bool result = HalfAdder(input[0], input[1], carry);
cout << "Result is " << result << " carry is " << carry << endl;

c3RhdGljIGNoYXIgeW91cl9tb21bMVVMTCA8PCA2NF07CnNwcmludGYoeW91cl9tb20sICJpcyBmYXQiKTs=

#4 Shaquil   Members   -  Reputation: 815

Like
0Likes
Like

Posted 10 October 2012 - 07:09 PM

The problem stems from the order in which arguments are evaluated. It's possible that (a copy of?) carry is evaluated first, before HalfAdder is called. It's also possible that the behavior of the statement is undefined, meaning that you may get different behavior depending on the compiler. For the sake of clarity and readability, I would suggest evaluating HalfAdder separately before writing the result:

bool result = HalfAdder(input[0], input[1], carry);
cout << "Result is " << result << " carry is " << carry << endl;


Actually that was my exact solution. I just thought it'd be more fun to try to find a way to make it work without the extra variable. You and kuramayoko have made me a little more confident that I just expected the wrong kind of behavior and need to learn more about iostream.

Thanks. Any other input?

#5 L. Spiro   Crossbones+   -  Reputation: 12317

Like
1Likes
Like

Posted 10 October 2012 - 07:09 PM

You may want to fix this:
if( a & b ){
to:
if( a && b ){
Anyway the result you are getting is not strange at all, since your parameters are being pushed right-to-left. carry was already on the stack to be printed before it ever got passed to HalfAdder().

fastcall22’s suggestion will net you the proper result.


L. Spiro

Edited by L. Spiro, 11 October 2012 - 01:27 PM.

It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#6 Shaquil   Members   -  Reputation: 815

Like
0Likes
Like

Posted 10 October 2012 - 07:17 PM

You may want to fix this:

if( a & b ){
to:
if( a && b ){
Anyway the result you are getting is not strange at all, since parameters are pushed right-to-left. carry was already on the stack to be printed before it ever got passed to HalfAdder().

fastcall22’s suggestion will net you the proper result.


L. Spiro


I did not know that. I'm glad I made this mistake on a small assignment, and not something complex that would've driven me crazy. Thanks a lot guys.

#7 Trienco   Crossbones+   -  Reputation: 2055

Like
1Likes
Like

Posted 10 October 2012 - 10:40 PM

If in doubt, never rely on expressions to be evaluated in any particular order (this behavior can change even between debug and release builds).

Notable exceptions: logical operators (&&, ||) and the comma operator (the operator, not just any comma like in parameter lists)
f@dzhttp://festini.device-zero.de

#8 Álvaro   Crossbones+   -  Reputation: 11943

Like
2Likes
Like

Posted 11 October 2012 - 01:36 AM

What Trienco is saying is that you should get familiar with the notion of "sequence point".

If you don't want the extra variable, break up the `cout << ...'statement into two. As long as there is a `;' in between the printing of the two values, you'll be fine (because `;' introduces a sequence point).

#9 Shaquil   Members   -  Reputation: 815

Like
0Likes
Like

Posted 11 October 2012 - 08:18 AM

What Trienco is saying is that you should get familiar with the notion of "sequence point".

If you don't want the extra variable, break up the `cout << ...'statement into two. As long as there is a `;' in between the printing of the two values, you'll be fine (because `;' introduces a sequence point).


Thanks for the link!

#10 Bregma   Crossbones+   -  Reputation: 4769

Like
1Likes
Like

Posted 11 October 2012 - 10:06 AM

Anyway the result you are getting is not strange at all, since parameters are pushed right-to-left....

Or left-to-right. Or as a thunk. Or passed in registers. Or the function is inlined and aliases are hoisted.
Stephen M. Webb
Professional Free Software Developer




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS