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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.