goto , for 循环 问题

davidxcl 2011-03-15 08:57:00
#include <iostream>
using namespace std;
int main
{
goto abc;
int sum;
abc:
cout<<sum<<endl;
}
输出一个随机数 提问:goto语句不能跳过声明么?

#include <iostream>
using namespace std;
int main
{
goto abc;
int sum = 0;
abc:
cout<<sum<<endl;
}
报错 提问:给sum初始化以后 为什么不能通过编译?

#include <iostream>
using namespace std;
int main()
{
for(int i = 1; i < 100; i++)//换成do while 形式的也一样
{
int sum = 0;
sum = sum + i;
}
cout<<sum<<endl;
}
报错sum未声明 提问:这次又和上面有啥区别 for 循环内部声明的变量,出了循环后不能继续使用?
#include <iostream>
using namespace std;
int main()
{
for(int i = 1; i < 100; i++)
{
int sum;
sum = sum + i;
}
cout<<sum<<endl;
}
这个程序和上一个一样报错







...全文
97 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wizard_tiger 2011-03-16
  • 打赏
  • 举报
回复
在for循环中定义的sum变量是一个局部变量,从循环外部不能访问。
cranium 2011-03-15
  • 打赏
  • 举报
回复
不管讨论结果是什么,直接放弃goto是肯定明智的
davidxcl 2011-03-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 c395565746c 的回复:]

不是goto不能跳过声明 。。而是局部auto变量的声明必须紧靠花括号。。
[/Quote]


我用的c++.............
hjs1122 2011-03-15
  • 打赏
  • 举报
回复
第一个是跳过了定义,第二个是使用了局部变量!
「已注销」 2011-03-15
  • 打赏
  • 举报
回复
不是goto不能跳过声明 。。而是局部auto变量的声明必须紧靠花括号。。

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧