Thread: How does a function call work?

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    9

    How does a function call work?

    Hi,

    Code:
    int i = 1;
    void f()
    {
        i = 2;
    }
    
    int main()
    {
        printf("%d\n", i);
        {
            int i = 3;
            f();
            printf("%d\n", i);
        }
        printf("%d\n", i);
    }
    When running the code, the value of the global variable is changed, but why? Why doesn't the value of that variable in the inner scope change?

    Thanks for help.

  2. #2
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Since f() doesn't have a local scope version of "i", then any reference to "i" in f() is to the global one.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    To follow up with rcgldr, when you call function f() on line 12, you do not inherit the scope where the function was called. You inherit the scope of the function definition. Since f is defined at global/file scope (the only place it can be -- C doesn't allow functions within functions), they only i within it's scope is the global i. The i defined on line 11 exists only within the scope of the curly brackets on lines 10-14 and shadows the global from the point of it's definition. Note, however that this "shadowing" only happens after i has been (re)defined (i.e. only lines after the definition), not for the whole scope. To illustrate this, you can swap the printf on line 9 and the curly brace on line 10, for the following:
    Code:
    $ cat foo.c
    #include <stdio.h>
    
    
    int i = 1;
    void f()
    {
        i = 2;
    }
    
    
    int main()
    {
        {
            printf("%d\n", i);  // global i from within the inner scope
            int i = 3;
            f();
            printf("%d\n", i);  // i declared 2 lines above -- shadowing the global
        }
        printf("%d\n", i);  // global i again, outside the scope of i's redefinition
    }
    
    
    $ ./foo
    1
    3
    2

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function Prototype, Function Call, and Function definition
    By dmcarpenter in forum C Programming
    Replies: 9
    Last Post: 04-09-2013, 03:29 AM
  2. Replies: 8
    Last Post: 07-08-2011, 01:16 PM
  3. Second scanf call with char does not work
    By madwizzy in forum C Programming
    Replies: 2
    Last Post: 02-15-2011, 10:37 PM
  4. Replies: 5
    Last Post: 10-17-2006, 08:54 AM
  5. my function doesn't work! it should work
    By Unregistered in forum C Programming
    Replies: 13
    Last Post: 05-02-2002, 02:53 PM