global and local variables

This is a discussion on global and local variables within the C++ Programming forums, part of the General Programming Boards category; i want a bunch of sub routines, but be able to use the variable in the sub routine, outside of ...

  1. #1
    Unregistered
    Guest

    global and local variables

    i want a bunch of sub routines, but be able to use the variable in the sub routine, outside of the sub routine. for example:

    void info (void)
    {
    do all this stuff which includes int a;
    }

    int main()
    {
    info();
    now here i want to use a, but outside the sub routine, for example
    cout a;
    }

    how do i do that? when i get home i'll paste the actual program im trying to do, thanks. It doesnt recognize a outside the sub routine.ANY HELP IS APPRECIATED

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    7
    you could have info return the value you want to use outside the function. For example:

    int info ()
    {
    do all this stuff which includes int a;
    }

    int main()
    {
    int a;
    a = info();
    cout << a;
    }

    hope this helps

  3. #3
    Unregistered
    Guest

    reference parameter

    when using a sub routine you can either yes assign the value of the subroutine to a variable in order to store and use it later in the program.

    Or you can use reference parameters


    declare your subroutine or subfunction

    void subroutine( variabletype &variablename);


    void subroutine(variabletype &variablename)
    {
    // when calculations are done in here now it will be passed back
    //up to the function in which it was called from
    }

    void main()
    {

    int a = 0;

    subroutine(a);

    cout <<a; // the new value will be there
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Local vs Global Variables
    By BENCHMARKMAN in forum C++ Programming
    Replies: 5
    Last Post: 07-03-2007, 06:17 AM
  2. Craps Program with Local Variables
    By tigrfire in forum C Programming
    Replies: 12
    Last Post: 11-09-2005, 09:01 AM
  3. local and global variables???
    By geo_c in forum C Programming
    Replies: 5
    Last Post: 08-23-2004, 04:02 PM
  4. Replies: 6
    Last Post: 01-02-2004, 01:01 PM
  5. Global Vs Local Variables
    By Waldo2k2 in forum C++ Programming
    Replies: 17
    Last Post: 11-11-2002, 07:51 PM

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