Re: Multiple variable rules in for() statement
Re: Multiple variable rules in for() statement
- Subject: Re: Multiple variable rules in for() statement
- From: Jonathon Kuo <email@hidden>
- Date: Thu, 12 Nov 2009 15:10:24 -0800
On Nov 12, 2009, at 12:14 PM, Greg Parker wrote:
On Nov 12, 2009, at 11:29 AM, Jonathon Kuo wrote:
I can't chance upon the right incantation for using both an
existing variable and an inline new one in a for loop. I've boiled
this down to a trivial show case, same results for both gcc 4.0.1
and 4.2.1:
int i;
. . .
for (i=0, int m=0; i<5; i++) { . . . };
printf("Final value of i: %d\n",i);
error: syntax error before ‘int’
error: syntax error before ‘)’ token
So I tried this:
int i;
. . .
for (int m=0,i=0; i<5; i++) { . . . };
printf("Final value of i: %d\n",i);
error: redefinition of ‘i’
Is there a rule that ALL initialized loop variables are either new
and local to the loop, or that none are? Surely Im doing something
wrong here!
The first clause of a C99 for loop may be a single expression, or a
single declaration. `i=0, m=0` is an expression: two assignment
expressions joined by the comma operator. `int i=0, m=0` is a
declaration, creating two new integer variables. `i=0, int m=0` is
invalid; the RHS of that comma is a declaration, but the comma
operator only allows expressions on both sides.
If you want both variables initialized to the same value, you can
use this:
int i;
for (int m = i = 0; i < 5; i++) { ... }
It's a declaration, whose initializater happens to have the side-
effect of assigning to another variable.
You can get the two variables initialized to different values:
int i;
for (int m = (i = 0, 10); i < 5; i++) { ... }
Again, a declaration with a complicated initializer.
But if you do that, keep in mind this irregular verb form:
My code is elegant.
Your code is sneaky.
His code is an ugly hack.
Okay, so yes, all initialized for loop variables are either new and
local to the loop, or none are, at least if one wishes to keep with
legible coding practices. Sort of non-obvious at first glance, but
makes sense.
Thanks!
Jon
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden