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(){...
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++);
}
}
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.