C++ 输出是什么。可见性和范围概念
我不明白编译代码时函数的输出是怎样的:C++ 输出是什么。可见性和范围概念,c++,C++,我不明白编译代码时函数的输出是怎样的: 0 1 1 我试着看这个,每次我只看到输出为: 1 1 1 我有什么遗漏吗?我知道我忽略了一些简单的事情 int foo(int a); int x =0; int main(){ int x = 4; int y=1; x=foo(x); cout << x << endl; cout << foo(y) << endl; x=foo(x);
0
1
1
我试着看这个,每次我只看到输出为:
1
1
1
我有什么遗漏吗?我知道我忽略了一些简单的事情
int foo(int a);
int x =0;
int main(){
int x = 4;
int y=1;
x=foo(x);
cout << x << endl;
cout << foo(y) << endl;
x=foo(x);
cout << x << endl;
return 0;
}
int foo(int n){
if(x==n){
return n--;
}
else
return x++;
}
intfoo(inta);
int x=0;
int main(){
int x=4;
int y=1;
x=foo(x);
cout这段代码有点混乱,但会尝试添加一些注释来解释发生了什么。主要的混乱来自foo()如何返回x++而不是++x,后者在递增全局值之前返回值
int foo(int a);
int x =0;
int main(){
int x = 4;
int y=1;
x=foo(x); // this returns 0 because global x has not been incremented yet.
cout << x << endl; // local x is 0 at time of assignment
cout << foo(y) << endl; // local y == 1 and global x == 1, so foo() executes n--
// this returns 1 and the post-decrement only affects the
// local variable within foo()
x=foo(x); // local x is 0, global x is 1 so return global x before incrementing
cout << x << endl;
return 0;
}
int foo(int n){
if(x==n){
return n--;
}
else
return x++;
}
intfoo(inta);
int x=0;
int main(){
int x=4;
int y=1;
x=foo(x);//由于全局x尚未递增,因此返回0。
你能从哪里得到第一个1
吗?你有两个变量叫做x
。这实际上是打印01
顺便说一句,这个返回n-;
在那里没有意义。@hazemnaceur Yesx
将递增一,但在此之前x
将被打印(当它仍然为零时).我认为您遇到的困惑是由于返回值是x++而不是++x;x在递增之前返回。