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 about 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 thought that a variables scope was limited by the inner-most surrounding curly braces { }
, but in the above example int i
appears to be limited in scope by the curly braces of the for-loop even though it is declared outside of them.
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.
The first thing I'd note is that you shouldn't confuse
and
The first is a control structure while the second is a function call. The control structure evaluates the text inside it's parens() in a very different way from how a function call does.
The second thing is... I don't understand what you're trying to say by:
The code you listed for the for loop is a very common structure in C and the variable "i" should, indeed, be available inside the for loop body. Ie, the following should work:
Am I misreading what you're saying?
In C99, you can declare your variables where you need them, just like C++ allows you to do that.
You can declare a variable in the control part of a 'for' loop:
You cannot declare a variable in the control part of a 'while' loop or an 'if' statement.
The C99 standard says:
The bottom line with respect to your
for
/fgets
confusion is that while "enclosing braces control scope" is the correct rule in C most of the time, there is another rule regarding scope in C99 (borrowed from C++) that says that a variable declared in the prologue of a control structure (i.e.for
,while
,if
) is in scope in the body of the structure (and is not in scope outside the body).