Consider following function declaration:
int abmeld(char *strsend)
which is called like this
abmeld(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] = "";
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?
You want to pass global variable to the function. It's simple that function you are using, requires parameter then you have to pass the parameters of the type of the argument that is required in the function. Here, there is no concern or issue for passing a global variable or a local variable.
Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.
Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.
Disadvantages of using Global VariablesToo many variables declared as global, then they remain in the memory till program execution is completed. This can cause of Out of Memory issue. Data can be modified by any function. Any statement written in the program can change the value of the global variable.
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.
(never forget that you code not only for the computer, but also for your colleagues -perhaps even yourself in a few months- who would have to improve your source code)
Also, functions using global state are typically not reentrant.
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) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With