C++ Scope

J

Jonathan Clements

Hi all,

Does 'for' have it's own scope? In one compiler I'm quite happy
writing:-

for(unsigned long i=1; i <= WHATEVER; i++) { /* something here */ } and
then (not nested)
for(unsigned long i=1; i <= WHATEVER2; i++) { /* something here2 */ }

Probably bad practice, but as far as I understand C++, 'i' should be a
temp within the scope of the for loop. Some compilers allow this, others
don't.... I'm wondering if I'm mis-understanding the scope rules or the
compilers are.

Thanks,

Jon.
 
K

Kurt Krueckeberg

Hi all,

Does 'for' have it's own scope? In one compiler I'm quite happy
writing:-

for(unsigned long i=1; i <= WHATEVER; i++) { /* something here */ } and
then (not nested)
for(unsigned long i=1; i <= WHATEVER2; i++) { /* something here2 */ }

Probably bad practice, but as far as I understand C++, 'i' should be a
temp within the scope of the for loop. Some compilers allow this, others
don't.... I'm wondering if I'm mis-understanding the scope rules or the
compilers are.
Your code is correct, even if some compilers incorrectly complain.
 
S

Stuart Golodetz

Jonathan Clements said:
Hi all,

Does 'for' have it's own scope? In one compiler I'm quite happy
writing:-

for(unsigned long i=1; i <= WHATEVER; i++) { /* something here */ } and
then (not nested)
for(unsigned long i=1; i <= WHATEVER2; i++) { /* something here2 */ }

Probably bad practice, but as far as I understand C++, 'i' should be a
temp within the scope of the for loop. Some compilers allow this, others
don't.... I'm wondering if I'm mis-understanding the scope rules or the
compilers are.

The compilers are. It's perfectly good (and common) practice to reuse loop
variables like i. If one of your compilers doesn't like it, just put:

#define for if(0); else for

at the top of each translation unit and it'll fix it.

HTH,

Stuart.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top