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++);
       }
   }
8

1 Answer

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest