If you were to omit the {} from an if or a for loop, would the following be permissible:
1 2 3 4 5
bool unknown;
if (somecondition)
bool test = unknown;
if (test)
cout << "This code compiles. " << endl;
Since test never goes out of scope, that means it would be declared and available for use later on, however, if somecondition were false, that means test would never have been declared at all.
Just something that dawned on me last night and I wanted to inquire about it.
1. Braces are not the scope resolution operator. That would be ::
2. An automatic object's lifetime is limited to the block it was declared in. Since the only thing in the block that starts on line 2 is the declaration of test, test will be initialized and immediately go out of scope. Braces aren't used to limit scope of automatic objects. They only allow you to include more than one statement as part of a block. The scope rules apply regardless of whether the block is wrapped in braces or not.
In fact, and I might be wrong here, that won't even compile because the compiler would notice that if somecondition is false, the if statement on line 4 will be trying to test something that doesn't exist.
Because the compiler doesn't analyze execution paths to figure out scopes. It only uses program structure for that.
It's different from dynamic object lifetime, which the compiler doesn't analyze, anyway:
1 2 3 4
int *obj;
if (something)
obj=newint;
std::cout <<*obj;
Assuming you meant int* obj...no, it wouldn't. obj is *still* only limited to the if statement's scope, so when you get the the std::cout, obj doesn't exist.