1

I found in a programm that code fragment

   {
      Aux_U16 =  16;

   }

so the question is : why there a this curly brackets. No keyword like if or switch are visible.

So what function have curly brakets in the programming language C, if they are written without any keyword

Peter
  • 1,629
  • 2
  • 25
  • 45
  • 1
    They indicate scope. Here is a link [http://msdn.microsoft.com/en-us/library/b7kfh662.aspx](http://msdn.microsoft.com/en-us/library/b7kfh662.aspx) – finlaybob Aug 19 '13 at 10:38

3 Answers3

2

It's sometimes nice since it gives you a new scope, where you can more "cleanly" declare new (automatic) variables.

Those braces are controlling the variable scope.And since variables with automatic storage are destroyed when they go out of scope.

It is simply to isolate a block of code that achieves a particular (sub)purpose. It is rare that a single statement achieves a computational effect I want; usually it takes several.

someone
  • 1,638
  • 3
  • 21
  • 36
0

{} brackets define the scope. These brackets must have been inside any function or method. If you are inside a function you can have {} blocks.

NOTE:- If you just add them and compile without any scope it will give you compile time error.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Normally they'd be used to constrain scope of a variable, but in with your example Aux_U16 = 16; no new variable is defined, so there must be a pre-existing variable named Aux_16, and beyond the end of the block it will continue to have whatever value it was last set to within the block.

Limiting the scope allows you to create, for example, a new variable named i, without needing to think about the state of any i outside of that block -- unfortunately, as in the example you gave, the compiler wouldn't notice the difference between definition and assignment, and you could end up corrupting a variable you thought you had protected.

The other common reason to find things that way is simply cut-and-paste. There's nothing wrong with free-standing blocks like this, and sometimes people just forget to delete the leftovers. Or they might have had temporary variables in there until they edited the code and they went away. Or they might mean it as a note to themselves that the code inside the block belongs together.

sh1
  • 4,324
  • 17
  • 30
  • Why would the compiler not notice the difference between definition and assignment? Doesn't definition need a type? – sleighty Feb 15 '19 at 19:02
  • I mean, the compiler wouldn't raise an error on the grounds that what you thought was a definition (if you thought that) has actually turned out to be an assignment because you forgot to use the type and the named variable was already defined in a parent scope. – sh1 Feb 17 '19 at 06:48