我想补充以上所有内容,在阅读以上内容之前,了解 c 编程的工作原理很重要。如果您只是编写开放代码,例如
Setup(){
int MainVar
}
MyRoutine(){
int myVar1;
int myVar2;
bool myVar3;
// Do stuff with myVars
MainVar = myVar1 - myVar2;
myVar3 = true;
}
然后任何人都可以直接从第二个程序访问 MyRoutine.myVar1。他们可以在 MyRoutine 中使用它之前更改 myVar2 的值,(1. 如果它不受保护,2. 如果他们知道它在那里,3. 如果他们知道它的作用)//Do stuff,从而改变了什么原程序员打算。
想象一下,您正在编写一个银行程序,并且让代码易受攻击,因此有人可以更改存款的价值,而无需在您的例程中更改来自另一家银行的 WITHDRAWL。其他人可能会出现并编写一个单独的程序来将该值更改 2 或 10,并在不存在的地方创造货币。但是,如果您在代码、例程、方法或变量之前加上 STATIC,则这些项目不能被另一个程序访问、查看和最重要的更改。
您可以在任何时候使用静态,使整个例程关闭,或仅关闭单个变量。因此允许其他人对您的代码的某些方面进行更改,但保留那些需要保护的方面。
在 MyRoutine 中设置静态会阻止某人从另一个程序执行 MyRoutine。由于 MyVar 是在 MyRoutine 中声明的,因此无法从其他程序访问它们。但是如果在程序的其他地方声明了一个名为 MainVar 的变量,它就可以访问。
Setup(){
int MainVar // This can be accessed from outside this code
}
static MyRoutine(){ // Because of static these vars are not
int myVar1;
int myVar2;
bool myVar3;
// Do stuff with myVars
MainVar = myVar1 - myVar2;
myVar3 = true;
}
在这里,只有带有静态的变量受到保护。myVar3 可以从其他地方读取,通知另一个例程交换已完成。
Setup(){
int MainVar // This can be accessed from outside this code
}
MyRoutine(){
static int myVar1; // This can NOT be accessed from outside this code
static int myVar2; // This can NOT be accessed from outside this code
bool myVar3; // This can be accessed from outside this code
// Do stuff with myVars
MainVar = myVar1 - myVar2;
myVar3 = true;
}