BaysideLizard 发表于 2023-11-14 22:53:28

S1E31:局部变量和全局变量

#include <stdio.h>
//鱼C论坛—BaysideLizard写于2023年11月14日

//int a,b=500;
//全局变量默认初始化为0。

void fun();

int main()
{
    int i = 500;

    printf("before,i = %d\n",i);

    for(int i = 0;i < 10;i++)
    {
//for中定义的i仅适用于for循环体内部。
      printf("i = %d\n",i);
    }

    printf("after,i = %d\n",i);


//全局变量实验
    extern int a,b;
//extern关键字:用来说明此变量在后边定义了。
    printf("In fun,before,a = %d,b = %d\n",a,b);
    fun();
    printf("In fun,after,a = %d,b = %d\n",a,b);


    return 0;
}

void fun()
{
    int b;

    extern int a;
    a = 123;//没有局部变量a,则修改全局变量a的值
    b = 789;//有局部变量b,则修改局部变量b的值

    printf("In fun,a = %d,b = %d\n",a,b);
}

int a,b=500;








运行结果:
before,i = 500
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
after,i = 500
In fun,before,a = 0,b = 500
In fun,a = 123,b = 789
In fun,after,a = 123,b = 500

Process returned 0 (0x0)   execution time : 0.059 s
Press any key to continue.









在FishC学C的第十五天

loveKYF 发表于 2023-11-15 13:34:26

很自律哦,未来的大佬(*I`*)
页: [1]
查看完整版本: S1E31:局部变量和全局变量