简体   繁体   中英

What is the use extra curly brackets in the code? What does it do?

This is a C program in which the code from "int k" and "for" loop are enclosed in the curly brackets. What is the purpose of those curly brackets?

   int main(){
       int k;
       {
           int k;
           for (k=0;k<10;k++);
       }
   }

There are no "unwanted braces" in this code. There is an anonymous block, which is not an error. In fact, it is allowed by the spec.

Your variable k is defined in the main scope, but then shadowed in the anonymous block.

int main() {
  int k = 0;
    {
    int k = 1;
    // do more stuff with k
    }
  // k is still 0 here.
}

When I was programming C, something like 1000 years ago, I would have had stern words for a dev on my team who tried using this trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM