可以在loop的括号内定义loop变量吗? [英] Is it ok to define the loop variable inside the loop's parantheses?

查看:115
本文介绍了可以在loop的括号内定义loop变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C相当陌生,但是在C#中有很多经验.我的大学老师告诉我,在纯" C语言中,初始化循环变量是错误的在循环中的括号内.他说它之所以运行是因为VS编译器.由于某些原因,演示文稿中的所有内容也显示了循环,并且其循环变量在括号之外声明.

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?

推荐答案

绝对没有错,但与您的编译器使用哪种C标准有关.

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

如果您的编译器早于C99使用标准,则在循环头中初始化变量将遇到类似这样的错误.

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

在后来的标准中,它得到了支持.这两种代码的唯一区别是,如果在循环头中声明了变量,则变量的 scope 仅限于循环.

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.

这篇关于可以在loop的括号内定义loop变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆