I’m looking at this page which says:
In C++ you can declare variables pretty much anywhere in your program. This is not the case with C. Variables must be declared at the beginning of a function and must be declared before any other code. This includes loop counter variables, which means you can’t do this:
for(int i = 0; i < 200; i++) {
Forgetting that you can’t declare variables just anywhere is one of
the most frequent causes of ‘it won’t compile’ problems for
programmers moving from C++ to C.
I’ve been using Objective-C for a while, and thus C, and I have no problems with a statement such as for(int i = 0; i < 200; i++) { and yet Objective-C is C, strictly, so what is this web page referring to?
The web page is inaccurately characterizing C89.
In C89, you could declare variables at the top of any block (not just at the start of a function), but not at any point during a block.
In C99 and beyond, you are not constrained to declare variables at the beginning of a block. Specifically, C99 allows you to write:
If you use GCC but need to retain compatibility with MSVC, then you can use
-Wdeclaration-after-statementto detect when you declare a variable after a statement (which C89 does not allow).Objective C presumably uses C99 rather than C89 as the standard it extends, so it allows variable declarations when needed.