Link to home
Start Free TrialLog in
Avatar of sandipmurmu
sandipmurmu

asked on

c programing

hi experts,
can we declare a variable inside for loops or others such.
eg. for(int i=0;i<=100;i++)

i m sandip.
Avatar of Mike McCracken
Mike McCracken

What do you mean/

mlmcc
Nope, that doesn't work in c, but has been introduced in c++ and is generally referred to as on-the-fly variable declaration.

.f
for(int i=0;i<=100;i++)  works just fine in C.

mlmcc
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It is allowed in the newer 1999 ISO C standard (known as C99).
Strictly speaking, it won't work in C. It will work in C++, though. C++ allows you to declare variables anywhere in your program so that you don't have to go through the process of declaring everything right at the start of the function, but at your ease, you can just declare more and more variables anywhere whenever you need them.  

mlmcc said that it'll work on C, but probably he's not tried it in a pure C compiler. C++ compilers will allow it. However, I guess that if you save the file with a .C extension (instead of .CPP), then even a C++ compiler will report an error.

Mayank.
Can I disagree, Mayank? As I just stated above, it is valid in C99, which is "pure C".
Checked it on http://home.tiscalinet.ch/t_wolf/tw/c/c9x_changes.html

You're right. Its allowed.

Mayank.
You will most likely have to set compiler switches though, to enable compilation conforming with c99 standard.

.f
sandipmurmu:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
I believe I answered it.

mlmcc
(Sorry mlmcc) I think fl0yd, ozo, myself (burtdav) and mayankeagle were on the right track. There's definitely an A to be given between us. I'd be happy to take the points if none of the other 3 want them.
As long as the points don't go to mlmcc, I'm happy with anything. My suggestion would be to split points between burtdav (first one to draw attention to the evolution of c) and mayankeagle for the helpful link.

.f
Thank you. My recommendation was also to split points between burtdav, ozo, fl0yd and mayankeagle.
I think it'd be classy to split 20 points 4 ways.
Then again, points are nothing but a side effect. In essence choosing answers will make it easier for others searching through PAQ's finding an answer quickly.

.f
>> it'd be classy to split 20 points 4 ways

if its an A grade, then its still 20 points to each. Anyways, hardly matters!
Well chosen, AnnieMod.