2

I am looking over an Xcode project I downloaded and am seeing code syntax that I am unfamiliar with:

enter image description here

The braces don't belong to a method signature, or any other conditional statement, they are just floating there. What is the point of this? Purely for code segregation/readability purposes?

Lizza
  • 2,769
  • 5
  • 39
  • 72

3 Answers3

7

This is just block scope; and is the same in C and C++. Any variables declared within the block are inaccessible outside of it. I commonly use it in switch statements:

switch(x) {
case 1: {
    const char *s = "hi";
}
break;
case 2: {
    const char *s = "ho";
}
break;
// etc.
}

Note that there are two variables called s, neither of which interfere with the other as they are within their own scope.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

The declarations within the scope enclosed by the braces will be confined to that scope, so label, icon, and button will not be visible outside of it. As such it provides locality which is generally considered to be good.

1

Legacy code needed { } in order to do declarations at all

In C89, you couldn't just do int i; anywhere; declarations were only valid at the beginning of blocks.

check this for more explanation

Why enclose blocks of C code in curly braces?

Community
  • 1
  • 1
Priyatham51
  • 1,864
  • 1
  • 16
  • 24