Thread: main to function question

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    2

    main to function question

    How would I import the variables from main to a function without passing it to the function? In the example my teacher gave me, he only passed 3 items to the function, but used variables from the main in the function without passing it and did not declare them in the function. How is this possible?

    very rough example:
    Code:
    void example(stuff, stuff2, stuff3)
    {
    blah;
    blah2=stuff;
    blah3=hello;
    hello = stuff;
    }
    
    void main()
    {
    blah;
    blah2;
    char hello;
    int stuff, stuff2, stuff3;
    hello = blah;
    example(stuff, stuff2, stuff3);
    }
    Last edited by Rice; 09-18-2007 at 03:40 PM.

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    2
    Ok, I just called my teacher and he told me why. He declared them globally and I guess I didn't catch that in my notes.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If the variables are global then you can use them in main and in any other function.

    If the variables are local to a function, then the only way to use them or their values in another function is to pass them as arguments or return them.

    Generally global variables are not good design. Of course, a teacher who teaches void main() (it should be int main()) might also be teaching global variables even if their use is a bad idea, so that makes sense that it's your answer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  2. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Question on function syntax and calling function
    By cbrman in forum C Programming
    Replies: 10
    Last Post: 10-05-2003, 05:32 PM
  5. I need help with passing pointers in function calls
    By vien_mti in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 10:00 AM