views:

144

answers:

5

What is the set of valid outputs for the following, according to the standard?

bool x;
cout << (x ? 1 : 2);

edit: unknown(google) has got it. In gcc my code was crashing because of sprite.setFrame(isPressed ? 0 : 1) with the conditional returning 28!

+2  A: 

If x is uninitialized, it can be both true or false. So the valid outputs are 1 or 2.

Gamecat
+1  A: 

Using a uninitialised variable is undefined.So anything can happen

yesraaj
Undefined behavior, or just an undefined value? Can you quote the standard?
Assaf Lavie
I'm not sure now if it's "undefined" or "unspecified". If it has an "unspecified" value, then it can be either true or false and so you can get 1 and 2. If behaviour is "undefined", then yes anything could happen.
Daniel Daranas
I mean, maybe the variable is _required_ by the standard to have some value (_any_ value) belonging, of course, to its possible set of values. So you can make a C++-standard-compliant compiler that after "int i; cout << i;"gives you "88", but not one that crashes.
Daniel Daranas
well, not ANYTHING can happen. I mean the code in the question (not Daniel's) can't output 55 or "my pet gerbil", and if it makes the computer start to dance and catch fire, you have other issues B-)
Brian Postow
Brian, first rule: don't assume anything :) see my edit.
+1  A: 

"++?????++ Out of Cheese Error. Redo From Start."

Paul Tomblin
+1 Terry Pratchett!
Brian Postow
Pratchett knows whereof he speaks.
TRiG
+1  A: 

Using a bool value in ways described by This Standard as "undefined" such as by examining the value of an unitialized automatic variable, might cause it to behave as it is neither true or false.

Welcome to the world of undefined behaviour. But first, why would you want to do that?

Anonymous
don't worry I won't :)
+1  A: 

Anything can happen, including fireTheMissiles().

cdv