c语言变量和作用,第3章 变量和数据类型 11、C语言变量的定义位置以及初始值...

在C语言中,变量可以定义在函数外面,也可以定义在函数里面,请看下面的代码:

#include

//在函数外部定义变量

int n = 100;

char c = '@';

int main(){

//在函数内部定义变量

float f = 89.5;

char *str = "http://c.biancheng.net";

//输出变量

printf("n: %d\nc: %c\nf: %f\nstr: %s\n", n, c, f, str);

return 0;

}

#include

//在函数外部定义变量

int n = 100;

char c = '@';

int main(){

//在函数内部定义变量

float f = 89.5;

char *str = "http://c.biancheng.net";

//输出变量

printf("n: %d\nc: %c\nf: %f\nstr: %s\n", n, c, f, str);

return 0;

}

运行结果:

n: 100

c: @

f: 89.500000

str: http://c.biancheng.net

我们在 main() 函数外部定义了变量 n 和 c,在函数内部定义了变量 f 和 str,它们都可以通过 printf() 输出。也就是说,在函数外部定义的变量在函数内部也可以使用。

在函数外部定义的变量叫做全局变量(Global Variable),在函数内部定义的变量叫做局部变量(Local Variable),它们的区别将会在《C语言函数》一章中详细说明。这里大家只要明白,变量也可以在 main() 函数外面定义即可。

微软编译器和GCC的区别

VC和VS都使用微软的编译器cl.exe。微软编译器规定,变量要在函数开头定义。也就是说,在定义变量之前不能有其他代码。例如,下面的例子就是错误的:

#include

#include

int main(){

int a = 100, b = 200, c;

c = a + b;

float d = 23.5, e = 22.899, f;

f = d + e;

//输出变量

printf("c = %d, f = %f\n", c, f);

system("pause");

return 0;

}

#include

#include

int main(){

int a = 100, b = 200, c;

c = a + b;

float d = 23.5, e = 22.899, f;

f = d + e;

//输出变量

printf("c = %d, f = %f\n", c, f);

system("pause");

return 0;

}

在定义变量 d、e、f 之前,有语句c = a + b;,这是错误的。更正后的代码为:

#include

#include

int main(){

int a = 100, b = 200, c;

float d = 23.5, e = 22.899, f;

c = a + b;

f = d + e;

//输出变量

printf("c = %d, f = %f\n", c, f);

system("pause");

return 0;

}

#include

#include

int main(){

int a = 100, b = 200, c;

float d = 23.5, e = 22.899, f;

c = a + b;

f = d + e;

//输出变量

printf("c = %d, f = %f\n", c, f);

system("pause");

return 0;

}

应当将变量 d、e、f 的定义移到语句c = a + b;之前。

而GCC编译器(C-Free、Dev C++、Code::Blocks 默认都使用GCC编译器)没有这个限制,变量可以在函数的任意位置定义,所以上面两段代码在GCC下都能够通过编译。

为什么相同的代码在不同的编译器下会产生不同的结果呢?这是因为它们遵循的标准不一样,我们会在下节《C语言的两套标准》中为您解开谜团。

变量的默认初始值

一个变量,即使不给它赋值,它也会有一个默认的初始值。因为每个变量都会占用一段内存空间,它的值就是这段内存中的数据。请看下面的代码:

#include

#include

int a1;

float b1;

char c1;

int main(){

int a2;

float b2;

char c2;

printf("a1 = %d, b1 = %f, c1 = %d\n", a1, b1, c1);

printf("a2 = %d, b2 = %f, c2 = %d\n", a2, b2, c2);

system("pause");

return 0;

}

#include

#include

int a1;

float b1;

char c1;

int main(){

int a2;

float b2;

char c2;

printf("a1 = %d, b1 = %f, c1 = %d\n", a1, b1, c1);

printf("a2 = %d, b2 = %f, c2 = %d\n", a2, b2, c2);

system("pause");

return 0;

}

可能的运行结果:

a1 = 0, b1 = 0.000000, c1 = 0

a2 = 17969204, b2 = 23.453390, c2 = 113

可以发现,全局变量的默认初始值是 0(它所占用的每一个字节都是0值),局部变量的默认初始值是随机的,是垃圾值,没有规律。这就告诫我们,使用局部变量之前一定要初始化,否则它的值是没有意义的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值