AOM*_*AOM 4 c variables pointers global function
新EE在这里只有很少的软件经验.在过去的几年里,在这个网站上看过很多问题,这将是我的第一个问题/帖子.还没有找到这个答案.
我想知道函数修改体内的全局变量(不将其作为参数传递),以及传递变量的地址之间的差异/动机.
以下是每个更清晰的示例.假设我正在声明一些函数"peripheral.c"(在"peripheral.h"中使用它们的原型,并在"implementation.c"中使用它们).
方法1:
//peripheral.c
//macros, includes, etc
void function(*x){
//modify x
}
Run Code Online (Sandbox Code Playgroud)
.
//implementation.c
#include "peripheral.h"
static uint8 var;
function(&var); //this will end up modifying var
Run Code Online (Sandbox Code Playgroud)
方法2:
//peripheral.c
//macros, includes, etc
void function(void){
//modify x
}
Run Code Online (Sandbox Code Playgroud)
.
//implementation.c
#include "peripheral.h"
static uint8 x;
function(); //this will modify x
Run Code Online (Sandbox Code Playgroud)
是避免使用"全局"变量的唯一动机吗?(另外,如果它只有文件范围,它真的是全局的吗?)
希望这个问题有道理.谢谢
接收指向变量的参数的函数更通用.它可用于修改全局变量,本地变量或任何变量.修改全局的函数只能执行该任务和该任务.
哪个是首选完全取决于上下文.有时一种方法更好,有时另一种方法更好.不可能明确地说一种方法总是优于另一种方法.
至于你的全局变量是否真的是全局变量,它是全局的,因为在你的进程中有一个变量的单个实例.