Ommitting Scope Resolution Operators from 1 statement control nests

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.
test does go out of scope - it's scope is the if (somecondition) statement - so it goes out
of scope at the end of line 3.

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.
@declan
You could do this, and it would not compile either
1
2
3
4
5
6
if(true)
   bool test = true;
else
   bool test = true;
//EDIT .....................
test = true;  //test was not declared 
Last edited on
Why not?
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=new int;
std::cout <<*obj;
Last edited on
Now that it was edited it makes sense ;)
¿Well would this work:

1
2
3
if (something)
     int *ob = new int;
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.
I just tested it and the following does in fact compile. Thank you helios.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int *obj;

int main()
{
    if(1)
        int *obj = new int;
    cout << *obj << endl;
}
Notice that the obj on line 11 is the one declared on line 5 and not the one from line 10
Thanks Bazzy, you really ruined my high.
Overriding scopes is one of the easiest ways to introduce subtle bugs into a program.
Here is an example directly form the C++ standard:
[Example:
1
2
if (x)
    int i;

can be equivalently rewritten as
1
2
3
if (x) {
    int i;
}

Thus after the if statement, i is no longer in scope. ]

Topic archived. No new replies allowed.