宣言区别? [英] Declaration difference?

查看:165
本文介绍了宣言区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的区别是什么,当我们使用循环前声明变量,并在循环定义变量时。

我说的这个情况。

  INT I;对于(i = 0; I< 100;我++);

 的for(int i = 0; I< 100;我++);


解决方案

在第一种情况下,假定该变量 I 也将被循环作为例如后使用

  INT I;对于(i = 0; I< 100;我++);输出(I =%d个\\ N,I);

尽管如此,它会好得多写以下方式

  INT I = 0;对于(; I< 100;我++);输出(I =%d个\\ N,I);

在这种情况下,我们将得到一个有效的可读code,而不需要理会是什么作为,例如循环内完成

  INT I = 0;/ *一些循环使用的I * /输出(I =%d个\\ N,I);

这是即使变量不会改变(分配)在循环或以其他code,而不是循环(通常是每code已被改变的倾向),然而,我们会得到一个有效的结果。

在第二种情况下,假设变量 I 将只在环路中使用

 的for(int i = 0; I< 100;我++);

我们不需要它的外循环值。因此,在这种情况下,该变量的寿命是由循环体的限制。外循环将是无形的,不是活的。

What is the difference when we declare variable before using in loop and when define variable in loop.

I am talking about this situation

int i;

for(i=0; i<100; i++);

and

  for(int i=0; i<100; i++);

解决方案

In the first case it is supposed that variable i will be used also after the loop as for example

int i;

for(i=0; i<100; i++);

printf( "i = %d\n", i );

Nevertheless it would be much better to write the following way

int i = 0;

for( ; i<100; i++);

printf( "i = %d\n", i );

In this case we will get a valid readable code without a need to bother what is done within the loop as for example

int i = 0;

/* some loop used i */

printf( "i = %d\n", i );

That is even if the variable will not be changed (assigned) in the loop or in some other code instead of the loop (usually each code has a tendency to be changed) nevertheless we will get a valid result.

In the second case it is supposed that variable i will be used only within the loop

for(int i=0; i<100; i++);

We need not its value outside the loop. So in this case the life of the variable is limited by the body of the loop. Outside the loop it will be invisible and not alive.

这篇关于宣言区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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