Thread: Why does this work

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    7

    Why does this work

    Code:
    #include <stdio.h>
    
    int getInt()
    {
        int b = 4;
        return b;
    }
    
    int main(int argc, char *argv[])
    {
        int a;
        a = getInt();
        printf("this is a %d\n", a);
        return 0;
    }
    ive been under the idea that you cant do this because b is out of scope after getInt(). Once it returns from that method, b is lost. But this runs fine, prints out 4.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The value in b is returned, not its address.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Oct 2009
    Location
    While(1)
    Posts
    377
    This is working because functions are meant for that only do some operations on some data, And return its value....

    b value is returned from the function getInt thats why it is working fine.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM