Quick question about global variable...

This is a discussion on Quick question about global variable... within the C Programming forums, part of the General Programming Boards category; Is it possible to make a variable (example: int a = 9) global while it is inside of a function?...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    10

    Quick question about global variable...

    Is it possible to make a variable (example: int a = 9) global while it is inside of a function?

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    2,432
    Not quite. When a variable is within a function, it only has function scope and is not defined outside of that function. Therefore, when program execution leaves that function, the value stored in the variable is lost.

    If you're just looking to keep the value of the variable intact when you leave the function (so you can come back to it later), look up the "static" keyword.

  3. #3
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Additionally, you should try to write your code so you do not require the use of global variables. You can read here why global variables are bad.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    10
    Thank you for your responses

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quick: Alternative to using global variable
    By abrownin in forum C++ Programming
    Replies: 1
    Last Post: 05-02-2010, 04:25 AM
  2. OOP question (global variable?)
    By VikingBow in forum C# Programming
    Replies: 5
    Last Post: 12-26-2007, 04:48 PM
  3. Global variable question
    By csisz3r in forum C Programming
    Replies: 10
    Last Post: 09-19-2005, 07:19 AM
  4. Static global variable acting as global variable?
    By Visu in forum C Programming
    Replies: 2
    Last Post: 07-20-2004, 08:46 AM
  5. global variable and header question
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 08-05-2002, 11:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21