Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Using Function Scope

Scope refers to the range of visibility of data items. Functions define their own scope. That is, when you define a variable in a function, it becomes a local variable for that function and takes precedence over other versions of the same variable. For example, you can define an integer named number and set it to 1 like this:

int number = 1;

And then you can also define an integer named number inside a function:

int number = 1;

void function(void)
{
  int number = 2;
  printf(
    "In the function the number is %i\n',
    number);
}

The local version of number will take precedence in the function, so here the printf() statement will display a value of 2 for number. If number hadn’t been defined locally in the function, the version from outside the function would have been used, and the printf() statement would have shown a value of 1.

In Objective-C, any code block—that is, code enclosed in curly braces such as function bodies or the bodies of if statements—defines its own scope, so local variables will always take precedence over variables defined outside the code block.

To use function scope:

  1. Create a new program named functionscope.m.
  2. In functionscope.m, enter the code shown in Listing 4.9.

    This code declares an integer named number displays its value in main(), and then calls a function.

    Listing 4.9. Starting functionscope.m.

    #include <stdio.h>
    void function(void);
    int number = 1;
    int main()
    {
      printf("In main the number is %i\n",
        number);
      function();
      return 0;
    }
           .
           .
           .

    Listing 4.10. The functionscope.m program.

    #include <stdio.h>
    void function(void);
    int number = 1;
    int main()
    {
      printf("In main the number is %i\n",
        number);
      function();
      return 0;
    }
    
    void function(void)
    {
      int number = 2;
    
      printf(
        "In the function the number is %i\n",
        number);
    
        {
          int number = 3;;
          printf(
          "In the block the number is %i\n",
          number);
        }
        printf(
        "After the block the number is %i\n",
        number);
    }
  3. Add the function that redefines number locally as well as in a code block (Listing 4.10).
  4. Save functionscope.m.
  5. Run the functionscope.m program.

    You should see the following:

    In main the number is 1
    In the function the number is 2
    In the block the number is 3
    After the block the number is 2
  • + Share This
  • 🔖 Save To Your Account