C++ 函数全解析:从基础到实战应用
1. 全局变量的陷阱
在编程中,有些人会采用一种方法,即不传递参数,而是将变量设为全局变量(不在任何 {} 内),而非局部变量(在 main 或其他函数的 {} 内)。以下是一个在屏幕上绘制十字的示例代码:
//Program to draw a cross on the screen
#include "SSDL.h"
//GLOBAL VARIABLES: THE EIGHTH DEADLY SIN
int x = 40, y = 40;
int distanceToEnds = 20;
//Prototypes
void drawCross ();
int main (int argc, char** argv)
{
//draw three crosses
drawCross();
x = 80; y = 30; distanceToEnds = 15; drawCross();
x = 110; y = 50; distanceToEnds = 40; drawCross();
SSDL_WaitKey();
return 0;
}
void drawCross ()
//draw a cross centered at x, y, with distance to ends, all global
{
SSDL_RenderDrawLine (x-distanceToEnds, y, x+distanceToEnds, y)
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



