Is it ok to define the loop variable inside the loop's parantheses?

妖精的绣舞 提交于 2020-05-15 19:26:08

问题


I am quite new to C but have a lot of experience in C#. My college instructor told me that in "pure" C, it is wrong to initialize the loop variable inside the loops parantheses. He said that it runs because of the VS compiler. For some reasons, all the material in the presentation also shows loops with their loop variable declared outside the parantheses.

for (int i=0; i < 5; i++)
{
   //He says that this is wrong, and you will lose points in tests for that
}

int i;
for (i=0; i < 5; i++)
{
   //Says it should be done like that (i declared outside loop)
}

Does it really matter? Do some compilers fail to recognize it? Will I lose points on a test?


回答1:


It's definitely not wrong, but a matter of which C standard your compiler uses.

If your compiler uses a standard earlier then C99, then initialising a variable in the loop header will through an error like so.

$ gcc loop.c 
loop.c: In function ‘main’:
loop.c:5: error: ‘for’ loop initial declaration used outside C99 mode

In later standards its supported then. The only difference of both styles for your code then is the scope of the variable is limited to the loop if the declared in the loop header.

So, by not initializing in the loop header, you make your code a little more portable or standard/compiler independent. But most people I know certainly use both styles.




回答2:


It is OK in the newer C versions.

But there is a distinct difference. i has different scope.




回答3:


There is no difference between the two versions when compiling with a modern compiler which fits to the C99 standard or above instead of when defining i inside of the parentheses, i has its scope and lifetime only inside of the according loop.

Outside of the according loop, the i you use inside the loop does not exist. You can´t use it f.e. twice for another loop.

When you try to compile code on a compiler/ compiler version, that is build up to a C standard before C99 with the definition of i inside of the parentheses, you will get an compilation error, just because it was not introduced to the language yet.

Both techniques have their advantages and downsides.

It is a reason of what compiler or compiler version you use, if you want to use i after the relative loop and nonetheless a matter of style and personal taste.

Will I lose points on a test?

Well, if he/she explicitly insists on this one (even if you use a modern compiler), I would not try to bother him/her and just declare i before the relative loop and everything is fine.

It is also sometimes (if not common) prohibited to use techniques not learned in the class. It might be that this is a nit-picking but matching example for this.



来源:https://stackoverflow.com/questions/61059550/is-it-ok-to-define-the-loop-variable-inside-the-loops-parantheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!