m*********a 发帖数: 3299 | 1 void f(){
int i;
cout<
}
void g(){
int i;//share the same address of f() i, why?
i=9999;
cout<
}
int main() {
f();//i is random
g();//print i=9999
f();//whoa!!!!print i=9999. Change in g can affect change in f()
g();//print 9999
return 0;
} |
f****4 发帖数: 1359 | 2 建议你找本 C++ primer看看就都明白了
【在 m*********a 的大作中提到】 : void f(){ : int i; : cout<: } : void g(){ : int i;//share the same address of f() i, why? : i=9999; : cout<: } : int main() {
|
X****r 发帖数: 3557 | 3 就C++语言的规定来说,未初始化的自动变量的内容是未定义的,也就是说实现里出现
任何值都不算错。
就这个具体情况来说,因为f的i和g的i刚好用了同一个地址,所以出现你所看到的现象
。但是这个并不是确定的,因为在不同的体系结构里这个刚好同一个地址未必成立,而
且编译器的优化也有可能会影响结果,所以你并不能根据这个来写程序,也没有必要深
研,只要知道这个是未定义的不要用就行了,就像i++ + ++i的值是多少一样。
【在 m*********a 的大作中提到】 : void f(){ : int i; : cout<: } : void g(){ : int i;//share the same address of f() i, why? : i=9999; : cout<: } : int main() {
|
S*A 发帖数: 7142 | 4
这个难道不应该编译时发个使用没有初始化的变量的警告吗?
肯定打开一定级别得 -Wxxx flag 会警告这个。
【在 m*********a 的大作中提到】 : void f(){ : int i; : cout<: } : void g(){ : int i;//share the same address of f() i, why? : i=9999; : cout<: } : int main() {
|
w***x 发帖数: 105 | |
b*******s 发帖数: 5216 | 6 use -Wall and -Werror options if u are using gcc
【在 m*********a 的大作中提到】 : void f(){ : int i; : cout<: } : void g(){ : int i;//share the same address of f() i, why? : i=9999; : cout<: } : int main() {
|