KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
The section §3.9.1/6 from the C++ Standard says, Values of type bool are either true or false . Now consider this code, void f(bool b) { switch(b) //since b is bool, it's value can be either true or false! { case true: cout << "possible value - true"; break; case false: cout << "possible value - false"; break; default: cout << "impossible value"; } } int main() { bool b; //note : b is uninitialized f(b); return 0; } Compile F:\workplace>g++ test.cpp -pedantic Run. Output : impossible value Unexpected output? Well, not really, as the Standard reads in the footnote of §3.9.1/6 that: Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false . So no matter how many times I compile and run this program, I get the same output : impossible value . However, if I change it a bit - removing the function f() from the picture, and write the switch block in main() itself: int main() { bool b; //note : b is uninitialized switch(b) //since b is bool, it's value can be either true or false! { case true: cout << "possible value - true"; break; case false: cout << "possible value - false"; break; default: cout << "impossible value"; } return 0; } Then I compile and run this program, I don't get impossible value as output; no matter how many times I repeat this, I never get impossible value . I'm just curious t
Tags (comma-separated)
Save Edits
Cancel