c***2 发帖数: 838 | 1 file a.c
int var=10;
file b.c
float var;
int func(...){
...
var=2.5;
...
}
then compile two file together, what will happen to var? |
s*****n 发帖数: 5488 | 2 var is file scoped. so nothing will happen. it is just the file scoped var.
【在 c***2 的大作中提到】 : file a.c : int var=10; : file b.c : float var; : int func(...){ : ... : var=2.5; : ... : } : then compile two file together, what will happen to var?
|
r*********s 发帖数: 2157 | 3 我怎么记得会有问题啊
你应该用 extern, means在别处有定义
或者用static使var 只在这个file的scope |
a****o 发帖数: 686 | |
h**6 发帖数: 4160 | 5 同意这种说法。
【在 r*********s 的大作中提到】 : 我怎么记得会有问题啊 : 你应该用 extern, means在别处有定义 : 或者用static使var 只在这个file的scope
|
c***2 发帖数: 838 | 6 1) Yes, if intending to use the same var, 'extern' shall be used.
2) The interviewer says, this is a coding error and asks what will happen.
my answer is to upgrade var as float. but he says compiler will truncate it
to int.
just tried: my answer is right:
a.c |
y*******o 发帖数: 6632 | 7 NO PROBLEM FOR in c file at all.
will be a problem in h file if included.
if in file b.c
file b.c
extern int var;//cause a collusion the int var is available in b.c now
float var;
int func(...){
...
var=2.5;
...
} |
K******g 发帖数: 1870 | 8 我不觉得有问题,compiler会默认static,所以就是file scope
如果你要使用在另外一个文件定义的变量,就必须用extern 去declare一下
如果不想用,只要不是在header file里定义的,都是file local变量,没有任何关系。
【在 c***2 的大作中提到】 : file a.c : int var=10; : file b.c : float var; : int func(...){ : ... : var=2.5; : ... : } : then compile two file together, what will happen to var?
|
K******g 发帖数: 1870 | 9 你这个测试有意思,你如果把main先到a.c里去,直接打印var,打出来的应该是10吧。
你在哪个文件里用它,var就是哪个的定义
进一步,你在a.c里写个函数,让var+=10, 然后return var。
在b.c里调用那个函数,打印出来,应该就是20.
it
【在 c***2 的大作中提到】 : 1) Yes, if intending to use the same var, 'extern' shall be used. : 2) The interviewer says, this is a coding error and asks what will happen. : : my answer is to upgrade var as float. but he says compiler will truncate it : to int. : just tried: my answer is right: : a.c
|
c***2 发帖数: 838 | 10 good point. Anyway, this is a bad question. |