I ran across a piece of C# code today I had not seen before. The programmer defined a block of code using only curly braces (no if, class, function, etc).
{
int i = 0;
}
i++; //compile error
Is there a purpose to this other than making the code look more organized? Is it good, bad, or whatever practice to use this "floating" contexts?
In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true. See event loop.
For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
In Java when you open a curly brace it means that you open a new scope (usually it's a nested scope). One important thing to understand is that a variable that you'll define inside this scope (which end where you put the closing curly brace) will not be recognized outside of the scope.
90) Can the curly brackets { } be used to enclose a single line of code? While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line.
You can use an open and close set of curly braces to define a self containing block, which has its own scope.
This is generally not considered good programming practice, though.
Usually if someone is doing something like this, it's probably better to create a method/function in its place.
Any variable inside the "scope" of these curly braces will be out of scope outside of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With