Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# allow {} code blocks without a preceding statement?

Why does C# allow code blocks without a preceding statement (e.g. if, else, for, while)?

void Main() {     {   // any sense in this?         Console.Write("foo");     } } 
like image 525
Seldon Avatar asked May 26 '11 10:05

Seldon


People also ask

Why is %d used in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

Why do we write in C?

It was mainly developed as a system programming language to write an operating system. The main features of the C language include low-level memory access, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like an operating system or compiler development.

Why semicolon is used in C?

Role of Semicolon in C: Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


2 Answers

The { ... } has at least the side-effect of introducing a new scope for local variables.

I tend to use them in switch statements to provide a different scope for each case and in this way allowing me to define local variable with the same name at closest possible location of their use and to also denote that they are only valid at the case level.

like image 118
João Angelo Avatar answered Oct 08 '22 05:10

João Angelo


In the context you give, there is no significance. Writing a constant string to the console is going to work the same way anywhere in program flow.1

Instead, you typically use them to restrict the scope of some local variables. This is further elaborated here and here. Look at João Angelo’s answer and Chris Wallis’s answer for brief examples. I believe the same applies to some other languages with C-style syntax as well, not that they’d be relevant to this question though.


1Unless, of course, you decide to try to be funny and create your own Console class, with a Write() method that does something entirely unexpected.

like image 28
BoltClock Avatar answered Oct 08 '22 04:10

BoltClock