正在通过全局变量问题的功能? [英] Is passing global variables to functions problematic?

查看:120
本文介绍了正在通过全局变量问题的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的函数声明:

int abmeld(char *strsend)

这就是所谓的这样

which is called like this

abmeld(str);

其中 STR 声明,并在程序文件的开始(包括之后)初始化这样一个全局变量:

where str is a global variable declared and initialised at the start of the program file (after the includes) like this:

char str[300] = "";

现在我已经知道这是不必要的code(你可以访问和任何函数内修改字符数组没有传递给它反正),但这个其实不然有问题?

Now I already know this is unnecessary code (you can access and modify the char array from within any function without passing it anyways), but is this actually otherwise problematic?

有没有后果(如硬错误的可能性,或未定义行为)可以发生,因为通过一个已经在全球范围内的变量函数的结果?

Are there consequences (like hard error possibilities, or undefined behavior) that can happen as the result of passing an already globally scoped variable to a function?

推荐答案

我要说的正好相反,它几乎从来没有问题通过一项全局函数(它通常是脏使用大量的全局变量中,$ C $ç变得不可读)。

I would say the opposite, it is almost never problematic to pass a global to a function (and it is usually dirty to use a lot of globals, the code becoming unreadable).

这要看轻(或根本没有)对全球状态的功能往往是更可读的,也比使用了很多全球性(甚至静态)变量的函数更容易理解。在许多功能改变了全局变量,使你的程序凌乱的理解。

A function which depends lightly (or not at all) on the global state is often more readable and more understandable than a function using a lot of global (or even static) variables. A global variable changed in many functions makes your program messy to understand.

(永远不会忘记你code不仅为电脑,也为你的同事甚至-perhaps自己在谁必须提高你的源代码code几个月 - )

此外,使用全局状态的函数通常不折返

Also, functions using global state are typically not reentrant.

最后,未定义行为大多是正交全球VS参数数据。特别是,一个缓冲区溢出可以与一个全局变量发生两者,或者与指针一些阵列(如一个参数或者一些局部变量)。

At last, undefined behavior is mostly orthogonal to global vs argument data. In particular, a buffer overflow can occur both with a global variable, or with a pointer to some array (such as an argument or some local variable) .

拇指的很粗糙的规则是,以避免超过7加载项开发商的大脑(神奇数字7,+或 - 2 );因此,民间传说规则,以避免超过7论据或超过7全局。

A very crude rule of thumb would be to avoid loading the developer's brain with more than 7 items (magical number 7, + or - 2); hence the folklore rule to avoid more than 7 arguments or more than 7 globals.

这篇关于正在通过全局变量问题的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆