Every time they talk about global variables, it's generally considered "bad practice" to use them unless there is a compelling reason to.

#defined CONSTANTS

on the other hand, seem to be fair game.

Why is that, since at the end of the day there is really not much difference between the two? Both are basically variables that represent a certain value that you can use anywhere in your program.


at the end of the day there is really not much difference between the two

Not really..

#defined CONSTANTS are simply "names" that are to be replaced (as in "copy&paste") by the preprocessor right before compiling. But in the end, they're just that: constants. There's no way a function or subroutine can access them and change them at runtime, because once your program got compiled, they got converted to (e.g.) numbers.

On the contrary, global variables can be accessed and changed by any subroutine. This may not seem like a big deal, but once your software starts to grow (like in hundreds of modules and thousands of subroutines) it can become a nightmare to track down every place you alter them.

Even worse: imagine you're working with some other programmers, each of you is hacking some modules, and you have some global variables that anyone can access and change. And suppose you realize a given global variable is not needed anymore, or should be renamed, or should be initiated to a different value... Probably your change would affect other people's work, and you'll have to agree upon new values / names and usage... Not an easy task ;)

That's why passing variables as args is always recommended (as opposed to global scoping), like @BrendanRafferty suggested, because it becomes apparent in which function is every variable used and/or modified.

  • if i change the value of a global variable in one function, will the global variable in other function be changed? Feb 20 '15 at 15:34
  • Precisely: a global variable is not scoped to any function, so if any of them makes a change, the new value will be available "globally".
    – abelinux
    Feb 20 '15 at 17:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .