Redian新闻
>
a C question about global variable
avatar
a C question about global variable# JobHunting - 待字闺中
c*2
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?
avatar
s*n
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?

avatar
r*s
3
我怎么记得会有问题啊
你应该用 extern, means在别处有定义
或者用static使var 只在这个file的scope
avatar
a*o
4
of course 有问题。
avatar
h*6
5
同意这种说法。

【在 r*********s 的大作中提到】
: 我怎么记得会有问题啊
: 你应该用 extern, means在别处有定义
: 或者用static使var 只在这个file的scope

avatar
c*2
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
avatar
y*o
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;
...
}
avatar
K*g
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?

avatar
K*g
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

avatar
c*2
10
good point. Anyway, this is a bad question.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。