0

Possible Duplicate:
Variable declarations following if statements
Why this compile error

I am getting the error "Embedded statement cannot be a declaration or labeled statement" because I had a declaration of a variable following an if statement with no brackets. Anyway, that's the background, which brings me to this.

The following code is illegal

if (true) int i = 7;

However, if you wrap that in brackets, it's all legal.

if (true){ int i = 7;}

Neither piece of code is useful. Yet the second one is OK. What specifically is the explanation for this behavior?

Community
  • 1
  • 1
chetan
  • 51
  • 3
  • 8

5 Answers5

2

The first version has no expression statement, just a declaration after the if but if requires a statement to follow it.

The second version has a statement. A pair of {} brackets is already a statement, even if it is empty (the declaration does not count as a statement again).

1

Because you're declaring a variable means you're creating a statement. A statement block must be enclosed in brackets {}. Here you can read more about Statements

ionden
  • 12,536
  • 1
  • 45
  • 37
1

Neither piece of code is useful.

The compiler can't check for usefulness, it can only check for definite "un-usefulness":
If you would use the variable in the second one, the could might make sense.

However, in the first example, you can't use the variable i because it's already out of scope in the next line - you have no chance of adding another line that makes the declaration useful again.

Nevertheless, the second one should generate a warning like "Variable i is assigned but its value is never used."

Matthias
  • 12,053
  • 4
  • 49
  • 91
1

An embedded statement that is not enclosed in {} brackets cannot be a declaration statement or a labeled statement. for more details visit http://msdn.microsoft.com/en-us/library/ms173143.aspx

In addition to it, if you declare variable and just after that if condition ends and so variable scope ends. so it makes sense that compiler will give an error. if you use {} instead, compiler will assume that you are going to use this variable somewhere between '{' and '}'

VRK
  • 400
  • 2
  • 5
0

Explained in very generic way: it's cause in the middle of the brackets compiler "presumes" it used.

Without a brackets there is no way the variable after being initialized can be used. Within brackets, instead, can.

See an excelent Skeet answer on my question and Eric Lippert comment too.

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123