Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Are local variables generally preferred over global?

  1. Feb 28, 2016 #1
    When I was taking my introduction to C class, our professor heavily stressed that we were supposed to use local variables except when indicated otherwise. When we used C for microcontrollers with the same professor, he had the same requirement.

    Does this reflect a standard among computer programmers, that local variables are preferred over global in terms of how the quality of a program is judged?
     
  2. jcsd
  3. Feb 28, 2016 #2

    Mark44

    Staff: Mentor

    Although there are good reasons to use global variables sparingly, there are many good reasons to prefer local variables over globals. For one, it's much easier to modify code, when needed, if the code doesn't modify global variables. For another, local variables hide the implementation of a routine better than when globals are used. Also, modular programming, with information passed in via parameters, decreases complexity, making it a better fit for large programming projects with multiple programmers.
     
  4. Feb 28, 2016 #3
    Generally, you want to encapsulate your data accordingly. Why would you create a global variable if it can be defined in another scope. It also helps with readability. For example consider a loop. Would it be easier to comprehend the loop if the counter variable is defined globally? No! You would want to define it in the scope, which is in the for() line. To answer your question it is essentially standard to create variables relative to their scope, so don't create globals when you don't need to! It may not be easy to see this in a small program but when things start hitting 1,000+ lines it can become a nightmare tracking down variable declarations-especially if they are global.

    As with most things, it depends on your application and design goals.
    Statically declared global variables are not stored on the stack or heap. Instead they go in the .data section.
    Maybe you have a limited stack size for security reasons and you want to save as much stack space as possible. One solution would be to statically allocate the data in .data instead of pushing all of it onto the stack.

    Or maybe you have a small chat program with a vector container of users. You might have some functions that need the vector of users.
    Code (Text):
    bool SendMessage(vector<string> USERS, string Message)
    bool SendPoke(vector<string> USERS)
    bool BanUser(vector<string> USERS)
    Depending on your design, you may want to make vector<string> USERS global to use them everywhere.
     
    Last edited: Feb 28, 2016
  5. Feb 29, 2016 #4

    rcgldr

    User Avatar
    Homework Helper

    One usage for global or static variables is for synchronization purposes, such as mutexes, semaphores, ... . Another usage is for interrupt driven routines, often part of a device driver in a typical operating system, or for an interrupt handler in a small embedded system, since parameters can't be passed to an interrupt driven function in the conventional sense. Sometimes an interrupt driven procedure goes through multiple interrupts, and one way to deal with this is by setting one or more pointers to function in advance of the next interrupt for which logical step should be performed through a series of interrupts. Yet another usage is shared memory between processes, where effectively all of the shared memory is "global".
     
    Last edited: Feb 29, 2016
  6. Feb 29, 2016 #5

    Svein

    User Avatar
    Science Advisor

    In my world, a global variable is an accident waiting to happen. Why? Since it is global, it will be visible to all and everybody - and that means that they will try to extract information from it and possibly change it. I subscribe to the "information hiding" principle - if somebody want some specific information from your code, write a snippet that returns the information. It is the same thing with objects - always make all variables private. If somebody wants to access those variables, create a method to return the information you want them to have.
     
  7. Feb 29, 2016 #6

    Svein

    User Avatar
    Science Advisor

    No. You would encapsulate it in an object and create methods to manipulate it.
     
  8. Feb 29, 2016 #7
    Which is why I said "Depending on your design". Not all designs are perfect.
     
  9. Feb 29, 2016 #8
    Yes. I've been working as a professional software developer for 20+ years and global variables are used sparingly and the more global variables a program has, the lower the perceived quality and ease of maintenance (also, your peers will make fun of you or deny you the rights to check in your code). The most common reason I come across global variables is to work around poorly designed function interfaces in multithreaded programs.
     
  10. Feb 29, 2016 #9

    rcgldr

    User Avatar
    Homework Helper

    Then that object may effectively be a global or a static. Encapsulation in that case just hides individual members, not the fact that a shared instance of an object may have scope outside of any single function, thread, and/or process.
     
  11. Mar 1, 2016 #10
    Okay, thanks for the advice.

    The context for this is that I'm in an intro simulation and numerical methods class and we having to make a MATLAB script for a project tjat will find roots of polynomials up to order 5 using six different methods. My approach is that I want the program to prompt the user to input the coefficients, confirm that the polynomial has only real roots (we haven't covered techniques to find complex roots yet) by evaluating the discriminant, and then call each root-finding algorithm as a separate function. For some reason, I can only get that to work if I set the coefficients and bounds for estimation as global variables.
     
  12. Mar 1, 2016 #11
    Best to strive even further, to make as many variables truly encapsulated as possible. If someone wants access, tell them to go away.
    Agreed. At least in OOP, even getters and setters are to be avoided as much as possible IMO. You want to reduce the number of ways in which external factors can change the internal state of a module, and avoid external dependency on the modules internal state. Try not to make public member functions modify internal state.
     
  13. Mar 1, 2016 #12

    Mark44

    Staff: Mentor

    IMO, it's reasonable to have the bounds for estimation as globals, but the coefficients should be a parameter (as a one-dimension array) of each the functions.

    Stylewise, the names of the bounds should be all caps, so that they really stand out.

    My $.02
     
  14. Mar 1, 2016 #13
    Besides all the good points here on style and encapsulation, there's another hardware-specific reason, mostly for embedded devices, to prefer local variables (stack allocated) to global or statically-allocated variables, which is speed.

    Most microprocessors have different types of internal RAM, with the lowest memory addresses typically being mapped to the fastest RAM. This is also typically the range which can be accessed using the least complex addressing mode (fewer and/or less complex CPU instructions). Since the stack is used for, for instance, return addresses when you call a function, it makes sense that the stack should reside in this fast access/fast addressing region.

    I've seen people, in code for embedded devices, allocate variables, which are used only in the local scope, statically as an attempt at optimization since the processor then doesn't have to "allocate the memory over and over again". This is completely backwards. The stack is fast, and global/statically-allocated variables might even get allocated to external (slow) RAM, depending on your system configuration. Allocating more space on the stack typically has zero overhead, since it just moves a stack pointer a bit further.

    In short: the stack is a wonderful place, but be careful with how much you fit on there (watch out for recursion!).
     
  15. Mar 1, 2016 #14

    Mark44

    Staff: Mentor

    Were you in that code or were there people in that code? :oldeek:
     
  16. Mar 1, 2016 #15
    It made sense when I wrote it!
     
  17. Mar 1, 2016 #16

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    Ease of access of global variables is both an advantage and a disadvantage. Be judicious and know why you are choosing global versus local. Protecting a variable is good. Making it harder and slower to get a variable value is bad. When you hide information, be sure you know who you are hiding it from, and why.

    Many real-time programs that I have seen have eventually run into execution time issues. It is discouraging when many programmer-years of effort has created elegant code that will not run fast enough. Function calls to access and/or set information are very slow.

    That being said. 99% of the variables in a program should not be accessible outside of the local scope. Make them local.
     
    Last edited: Mar 1, 2016
  18. Mar 2, 2016 #17

    Svein

    User Avatar
    Science Advisor

    Agree. But there is no rule that says that you have to accept the value in the "set" call. Creating a "set" method allows you to decide whether or not to change anything. A good idea is to return the "new" value, so the guy trying to change the variable can check if the "set" was successful.
     
  19. Mar 2, 2016 #18

    Svein

    User Avatar
    Science Advisor

    I heard that argument used when discussing system architecture with a professor in IT. His reply was: "Of course, if there is no requirement that the code should be correct, I can make it run extremely fast!"
     
  20. Mar 2, 2016 #19

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    However, if it doesn't run fast enough, it doesn't matter if it is correct or not. It will have to be rewritten. Good programmers can avoid misusing global variables. They can not speed up the hardware.
     
  21. Mar 2, 2016 #20

    Svein

    User Avatar
    Science Advisor

    Yes, of course.
    Easy. Wait a year. The hardware will be 20% faster...
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Are local variables generally preferred over global?
  1. Global variables. (Replies: 7)

  2. Why not local loops? (Replies: 33)

Loading...