Some errors in Visual Studio 2010 or C #? Or am I just dreaming?

I simply created a simple project with if statements to check if this statement is true, but then I came across something strange.

This is my sample code.

if(x ==1) { do something; } else if( x==2) { do something; } else if( x==3) { do something; } else if( x==4) { do something; } { do something; } 

No, you read it right. And I also scored this right. I left the else statement, but for this I created curly braces. When I compile, it works fine. It's some kind of mistake? Or am I just new to this? I just wanted to find out. Thanks for all the answers.

+6
source share
4 answers

Your last block of code without if/else if will be executed. Curly braces are intended to separate code and do not require conditional / iteration or any other predecessor to make sense.

To exaggerate, to further explain my thought:

 { { Console.WriteLine("This works"); int i; } // the variable i is out of scope and can't be referenced here } 

It is also possible.

According to a comment by @slugonamission , he brought up a wonderful moment. A code block also creates an area allocation for variables that are created inside this code block.

+14
source

It is always syntactically legal to surround any number of statements, including zero, in braces. The result itself is an expression.

You use this fact all the time; In fact, you used it half a dozen times in your example. The consequence of "if" is always one statement. In your example, this single statement is a block statement containing another statement.

+17
source

A set of curly braces defines a block of statements. You can make any set of statements a block, although the most useful is to use them after the control structure to place several statements in it. The syntax for a block operator requires only what happens after it is an expression — it can be either a single statement or a block statement (this is just another kind of statement).

A block outside the control statement does nothing but create a new area for local variables. I like to use them inside a case because cases do not automatically create a new area.

 switch (foo) { case 1: { int i; // local to this case! break; } case 2: { int i; break; } } 

Oh, and also this: Do not rush to claim that you found a mistake

+5
source

This is a valid syntax. The brackets themselves indicate only a separate coverage unit; in this case are completely unrelated to if - else if .

This way, the last block will always be executed in your code.

+2
source

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


All Articles