这篇文章主要介绍“c语言中的解释局部和全局作用域实例分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“c语言中的解释局部和全局作用域实例分析”文章能帮助大家解决问题。
变量的作用域是什么?
在继续了解局部和全局变量作用域之前,让我们了解作用域的含义。
简单来说,变量的作用域就是它在程序中的生命周期。
这意味着变量的作用域是整个程序中变量被声明、使用和可以修改的代码块。
在下一节中,您将了解变量的局部作用域
C 中变量的局部作用域——嵌套块
在本节中,您将了解局部变量如何在 C 中工作。您将首先编写几个示例,然后概括作用域原则。
▶ 这是第一个例子:
#include <stdio.h>
int main()
{
int my_num = 7;
{
//add 10 my_num
my_num = my_num +10;
//or my_num +=10 - more succinctly
printf("my_num is %d",my_num);
}
return 0;
}
让我们了解一下上面的程序是做什么的。
在 C 中,您用 {}分隔代码块。左花括号和右花括号分别表示块的开始和结束。
现在,编译并运行上面的程序。这是输出:
//Output
my_num is 17
您可以看到以下内容:
C 中变量的局部范围——嵌套块示例 2
▶ 这是另一个相关的例子:
#include <stdio.h>
int main()
{
int my_num = 7;
{
int new_num = 10;
}
printf("new_num is %d",new_num); //this is line 9
return 0;
}
在这个程序中,main()函数my_num在外部块中有一个整数变量。
另一个变量new_num在内部块中初始化。内部块嵌套在外部块内。
我们试图new_num在外部块中访问和打印内部块的值。
如果您尝试编译上面的代码,您会注意到它没有成功编译。您将收到以下错误消息:
Line Message
9 error: 'new_num' undeclared (first use in this function)
这是因为变量new_num是在内部块中声明的,其作用域仅限于内部块。换句话说,它对于内部块是本地的,不能从外部块访问。
基于上述观察,让我们写下以下变量局部作用域的通用原则:
{
/*OUTER BLOCK*/
{
//contents of the outer block just before the start of this block
//CAN be accessed here
/*INNER BLOCK*/
}
//contents of the inner block are NOT accessible here
}
C 中变量的局部作用域——不同的块
在前面的示例中,您了解了如何无法从块外部访问嵌套内部块中的变量。
在本节中,您将了解在不同块中声明的变量的局部作用域。
#include <stdio.h>
int main()
{
int my_num = 7;
printf("%d",my_num);
my_func();
return 0;
}
void my_func()
{
printf("%d",my_num);
}
在上面的例子中,
▶ 现在编译并运行上述程序。您将收到以下错误消息:
Line Message
13 error: 'my_num' undeclared (first use in this function)
如果您注意到 on line 13,该函数my_func()尝试访问在my_num函数内部声明和初始化的main()变量。
因此,变量的作用域my_num被限制在main()函数内,被称为函数局部的main()。
我们可以将这种局部作用域的概念一般性地表示如下:
{
/*BLOCK 1*/
// contents of BLOCK 2 cannot be accessed here
}
{
/*BLOCK 2*/
// contents of BLOCK 1 cannot be accessed here
}
C 中变量的全局范围
到目前为止,您已经了解了 C 变量的局部作用域。在本节中,您将学习如何在 C 中声明全局变量。
▶ 让我们从一个例子开始。
#include <stdio.h>
int my_num = 7;
int main()
{
printf("my_num can be accessed from main() and its value is %d\n",my_num);
//call my_func
my_func();
return 0;
}
void my_func()
{
printf("my_num can be accessed from my_func() as well and its value is %d\n",my_num);
}
在上面的例子中,
该变量my_num在函数main()和之外声明my_func()。
我们尝试访问函数my_num内部main(),并打印其值。
我们在函数my_func()内部调用main()函数。
该函数my_func()还尝试访问 的值my_num,并将其打印出来。
该程序编译没有任何错误,输出如下所示:
//Output
my_num can be accessed from main() and its value is 7
my_num can be accessed from my_func() as well and its value is 7
在这个例子中,有两个函数 -main()和my_func()。
然而,该变量my_num不在两个这两个函数中。这种对任何函数都不是局部的变量被称为具有全局作用域,称为全局变量。
这个全局变量作用域的原理可以总结如下:
//all global variables are declared here
function1()
{
// all global variables can be accessed inside function1
}
function2()
{
// all global variables can be accessed inside function2
}
关于“c语言中的解释局部和全局作用域实例分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注天达云行业资讯频道,小编每天都会为大家更新不同的知识点。