Tuesday, February 23, 2010

Programmer - Where can I legally declare a variable in C99?

Programmer Question

When I was first introduced to C I was told to always declare my variables at the top of the function. Now that I have a strong grasp of the language I am focusing my efforts on coding style, particularly limiting the scope of my variables. I have read this SO question on the benefits to limiting the scope and I came across an interesting example. Apparently, C99 allows you to do this...



for (int i = 0; i < 10; i++)
{
puts("hello");
}


I had always thought that a variables scope was limited by the inner-most curly brackets { }, but in the above example int i appears to be limited in scope by the for-loop's parentheses ( ) and the compiler will promptly give you an error if you try to use i inside the for-loop body.



I tried to extend the above example with fgets() to do what I thought was something similar but both of these gave me a syntax error.



fgets(char fpath[80], 80, stdin); See Note*



fgets(char* fpath = malloc(80), 80, stdin);



So just where exactly is it legal to declare variables in C99? Was the for-loop example an exception to the rule? Does this apply to while and do while loops as well?



Note*: I'm not even sure this would be syntactically correct even if I could declare the char array there since fgets() is looking for pointer to char not pointer to array 80 of char. This is why I tried the malloc() version.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails