Thread: Changing Global Variable

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    8

    Changing Global Variable

    Hey Guys,

    So, I will give a snip of code from one of my much larger programs that I am working on. what I am trying to do is change a global variable with a method that is called. It works and changes that global variable, but for some reason under certain circumstances that variable appears to get changed again without the function being called. I don't understand why. So here it is:

    [tag]
    Code:
    //Love me some global variables
    int num;
    char *cmds[10];
    char *typed, *prompt;
    
    void perror(string s)
    {
    	cout << s << endl;
    }
    
    char* promptCNG(char *line)
    {
    	string n;
    
    	line = strchr(line, '"');
    -> Find the first parenthesis set string to start from that point
    if(line == NULL)
    ->If there is no parenthesis yell+quit
    { perror("Use the right syntax!\n"); return NULL; } else { line = line+1;
    ->cut the initial parenthesis found
    line[strlen(line)-1] = NULL;
    ->cut last parenthesis of the pair
    n = line;
    ->strings are easier to append
    n = n + ": ";
    ->appending
    return (char*)n.c_str();
    ->convert back to char* and return it
    } } int main() { prompt = "I will do your bidding master: "; while(1 == 1) { typed = NULL; typed = readline(prompt); add_history(typed); if(typed[0] == 'P' && typed[1] == 'S' && typed[2] == '1') prompt = promptCNG(typed); else cout << endl; } return 0; }
    [/tag]

    What I would expect to see happen is my prompt will pop up and wait for input. If my input starts with the characters "PS1" then it should call my function to change my prompt which should then change my global variable and then forever more my prompt should be whatever was returned from my promptCNG function.

    And, for the most part is works except for if I do PS1 = " " which would make my prompt a spot of white space followed by the colon ( : ). It will change my prompt successfully to that but then the next time my mains while loop comes round it gets changed again without the function call and I have no prompt at all? I don't understand how that is happening. Any suggestions?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Which global variable did you try to change? n is a local variable, not a global one.

    And of course the whole point of a global variable is that it can be changed anywhere, not just this function. So you'd have to look at all the code to make sure you didn't change it somewhere else too.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Code:
    return (char*)n.c_str();
    After this the string n goes out of scope and deallocates its buffer. You are returning a dangling pointer. (And I suppose casting constness away from it is a terrible idea anyway.)
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User
    Join Date
    Nov 2010
    Posts
    8
    I have also tried changing the global variable from within the method instead of returning a value but also ran into the same problem. And, I can assure you that in my grand program the only method that ever references the global variable prompt is my method that I use to change it. Nowhere else is it mentioned so theoretically that should mean that it should never get changed again without the function call.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by trsmash
    And, I can assure you that in my grand program the only method that ever references the global variable prompt is my method that I use to change it.
    Famous last words? If indeed the global variable has such local scope, then change it to a local variable. Even as a static local it will be somewhat easier to trace.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Nov 2010
    Posts
    8
    A valid idea, but not exactly something that will work out for the purpose of my program. It is a global variable because it can be changed at different times during the running of the program. As a local variable that will no longer be possible and will cause a loss of some functionality.

  7. #7
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by trsmash View Post
    A valid idea, but not exactly something that will work out for the purpose of my program. It is a global variable because it can be changed at different times during the running of the program. As a local variable that will no longer be possible and will cause a loss of some functionality.
    You do realize you just contradicted your prior statement; that only the one function references the global variable.

    Tim S.

  8. #8
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472

    design

    i think if you find yourself running into headaches like this with something like a global then its time to ask yourself questions about your overall design
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rogster001
    i think if you find yourself running into headaches like this with something like a global then its time to ask yourself questions about your overall design
    Indeed, the description of the problem ("for some reason under certain circumstances that variable appears to get changed again without the function being called") is a classic example of a major problem with global variables, or perhaps global state in general. It makes it more difficult to reason about your program.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Nov 2010
    Posts
    8
    No, I don't believe so. I'm just learning so I'm not going to act like I know everything about coding. But, just because I said that the global variable is changed at different times during the running of the program does not mean that the global variable is accessed in multiples ways. if more info is necessary I can give.

    In the grand program the main takes in an input from a user. That input should be a command, or it can be a queue of commands separated by semicolons. The main first parses the line looking for semicolons. It then sends one by one the list of parsed lines to another method which parses each line again by looking for white space between words.

    The second parsing method first checks to see what the first 3 characters of the given line are. If they are a specific set of characters then my method to change the prompt is called. If not, then it goes about its business continues to run how it should which would simply be to run whatever command was given by the users input. The point being though, that the variable prompt is changed outside of the main from another method which can be called at variable times. Which is why to my understand why I would need it to be a global variable instead of it being local. (Which I did change it to a local and it works, but like I stated, loss of functionality). The ability to be able to change the prompt as one of the queued commands the user gives was something that I was hoping to keep, but the error I am suffering is keeping me from that goal.

    And, I have thought it to be a design flaw. I am new to this and it would make complete sense and I have changed my code up in many different ways for that same reason. I am just having a hard time seeing how the global variable that is changed only by one method which is only called under one very specific case (even if that method can be called at variable times) could be changed afterwards without the function call being made. But thanks for all the insight and help everyone. It definitely helps!
    Last edited by trsmash; 12-07-2010 at 03:20 PM. Reason: Major typos

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by trsmash
    The point being though, that the variable prompt is changed outside of the main from another method which can be called and variable times. Which is why to my understand why I would need it to be a global variable instead of it being local.
    Why did you rule out passing the prompt variable by reference?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Nov 2010
    Posts
    8
    ^^^^^ I'm not exactly sure on how to do that? I've heard of it, haven't figured out exactly what that means when it comes to coding. ^^^^^^

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by trsmash
    I'm not exactly sure on how to do that? I've heard of it, haven't figured out exactly what that means when it comes to coding.
    You could read the tutorial on references, but more realistically you should work through a structured text to learn C++, e.g., Accelerated C++.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Nov 2010
    Posts
    8
    Cool, thanx for the info.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. global struct variable best use
    By Kempelen in forum C Programming
    Replies: 2
    Last Post: 06-05-2009, 05:08 AM
  2. global variable at dynamic library
    By Mortissus in forum C++ Programming
    Replies: 2
    Last Post: 07-31-2007, 02:44 PM
  3. Assigning an address to a global variable.
    By edunia11 in forum C Programming
    Replies: 9
    Last Post: 08-11-2006, 12:52 PM
  4. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM
  5. Global variable question
    By csisz3r in forum C Programming
    Replies: 10
    Last Post: 09-19-2005, 07:19 AM