variable declaration in for()

  • Thread starter ballpointpenthief
  • Start date
B

ballpointpenthief

I recently sent some code to a friend to go over, and I was told that
c99 doesn't allow variable declarations in for()

in other words you can't do this:

for (int i; i<9; i++);

I can't see what the reason for this not being allowed.
Any comments on this?

Cheers, Matt
 
P

pete

ballpointpenthief said:
I recently sent some code to a friend to go over, and I was told that
c99 doesn't allow variable declarations in for()

in other words you can't do this:

for (int i; i<9; i++);

I can't see what the reason for this not being allowed.
Any comments on this?

(i) needs an initializer.
 
P

pete

sorry, schoolboy error
for (int i=0; i<9; i++);

Looks like valid C99 to me.
Code like that, is usually the first clue that I notice
which indicates that I'm looking at C99 code.
 
P

pemo

ballpointpenthief said:
I recently sent some code to a friend to go over, and I was told that
c99 doesn't allow variable declarations in for()

in other words you can't do this:

for (int i; i<9; i++);

I can't see what the reason for this not being allowed.
Any comments on this?

With an initialiser, it's perfectly legal - the scope of 'i' ending
with the statement/compund-statement following the for(), e.g.,

for(int i = 0; i < 10; ++i)
{
// use i.
}

// the i above is out of scope here.
 
B

Ben Pfaff

ballpointpenthief said:
I recently sent some code to a friend to go over, and I was told that
c99 doesn't allow variable declarations in for()

Your friend may be thinking of C89. This feature is new in C99.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top