Variable declarations following if statements

Posted by Anthony Pegram on Stack Overflow See other posts from Stack Overflow or by Anthony Pegram
Published on 2010-03-22T23:54:55Z Indexed on 2010/03/23 0:01 UTC
Read the original article Hit count: 311

Filed under:
|

An issue came up on another forum and I knew how to fix it, but it revealed a feature of the compiler peculiar to me. The person was getting the error "Embedded statement cannot be a declaration or labeled statement" because they had a declaration of a variable following an if statement with no brackets. That was not their intent, but they had commented out the line of code immediately following the if statement, which made the variable declaration the de facto line of code to execute. 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? I have a hypothesis, but I'd rather ask the brilliant people on stackoverflow.

© Stack Overflow or respective owner

Related posts about c#

Related posts about codeblocks