声明并在初始化循环变量 [英] Declaring and initializing variable in for loop

查看:113
本文介绍了声明并在初始化循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写简单

for (int i = 0; ...

而不是

int i;
for (i = 0; ...

在C或C ++?

(将变量 I 是循环内只能访问?)

(And will variable i be accessible inside the loop only?)

推荐答案

它用C ++有效

这是不是在C结果的原始版本法律
但被采纳为C99(当一些C ++特征进行排序回移植到C)的C部分结果
使用gcc

It was not legal in the original version of C.
But was adopted as part of C in C99 (when some C++ features were sort of back ported to C)
Using gcc

gcc -std=c99 <file>.c

变量里面for语句和环绕在声明有效。如果这是一个块语句则它是有效的对整个块的

The variable is valid inside the for statement and the statement that is looped over. If this is a block statement then it is valid for the whole of the block.

for(int loop = 0; loop < 10; ++loop)
{
    // loop valid in here aswell
}

// loop NOT valid here.

这篇关于声明并在初始化循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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