Look at this example:
int i;
for (i=1;i.......
and this:
for (int i=1;i........
What’s the difference between them?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first one declares the variable in the scope outside of the loop; after the loop has ended, the variable will still exist and be usable. The second one declares the variable such that it belongs to the scope of the loop; after the loop, the variable ceases to exist, preventing the variable from being inadvertantly/mistakenly used.
In C99, C++, Java, and other similar languages, you will find mostly the second syntax as it is safer — the loop index belongs to the loop and isn’t modified / shared elsewhere. However, you will see a lot of the former in older C code, as ANSI C did not allow the loop variable to be declared in the loop like that.
To give an example:
By contrast: