Cant declares a local variable inside a conditional statement

It is allowed:

        // scope_1
        int i = 100;
        if (i > 50)
        {
            // scope_2
            int a = 200;
        }

This gives an error:

        // scope_1
        if (100 > 50)
            int a = 200;

Is the reason that the second code example gives us an error due to areas? Thus, the compiler does not allow the declaration of the variable a inside a certain scope only if the conditional operator evaluates to true, because if it were resolved, the compiler could not figure out whether to allow the declaration of another variable named a in scope_1 ?

+3
source share
9 answers
if (100 > 50)
    int a = 200;

? , , , , .

, a if. . , , ? , , ; ( ), .

+13

if, . , ?

, if , , . , , -?

, .

+8

.

?

8.7.1 , "if" " ".

8 , , , , , , try, checked, unchecked, lock, using yield statement, .

?

, . ; . , , "if" :

if (x) int y = M();
else string y = N();

? ?

?

if(x) int y = M();
else y = N();
Q(y);

? , , Q (y)?

, . , , , , . , , .

, :

? ?

. :

http://ericlippert.com/2009/08/13/four-switch-oddities/

, , - , ?

. .

, ?

:

http://blogs.msdn.com/ericlippert/archive/2007/04/23/write-only-variables-considered-harmful-or-beneficial.aspx

+5

:

if (100 > 50)
    int a = 200;

, , "a", . l, .

( ):

if (100 > 50)
    int a = 200;

Console.WriteLine(a); // This makes no sense... What happens if 100 < 50????

, , , .

+3

{}. ,

.

        // scope_1
        int i = 100;
        if (i > 50)
        {
            // scope_2
            int a = 200;
        }

        // if you will try
        int anotherA = a; // a does not exist in the current context
+2

if {}, . , . , false, .

( #)

, {} , .

+2

, , ( ) , .

!

+1

" " a if.

C89 . C99 ( ) .

:

 if ( i )
   int a = 100;

- , . "if" . - , . .

, {}.

if ( ) statement

, .

:   { - }

(See also K & R 2ed A9.3 Compound Application)

As already noted, this is a C # question. The C # standard is discussed in section 15.2, but not so briefly. :) In principle, the declaration needs a block. The block needs brackets. The end of the story.

+1
source

You will get the error:

error CS1023: Embedded statement cannot be a declaration or labeled statement

This means that the syntax for the if statement requires an operator or block statement following the conditional expression.

if-stmt -> 'if' '(' expr ')' stmt ['else' stmt]  

stmt ->    if-stmt
     ->    do-stmt
     ->    ...etc...
     ->    '{' [declaration...] [stmt...] '}'

A declaration is not an instruction, so this is a simple syntax error.

+1
source

Source: https://habr.com/ru/post/1732401/


All Articles