Broad Network


Function Scope in C++

Scopes in C++ - Part 2

Forward: In this part of the series, I explain function scope in C++.

By: Chrysanthus Date Published: 25 Aug 2012

Introduction

This is part 2 of my series, Scopes in C++. In this part of the series, I explain function scope in C++. As I said in the previous part of the series, scoping in C++ is focused on the C++ block, which consists of statements within curly brackets.

A Function
A function definition, begins with the prototype without the semicolon, followed by a block of statements. The block of the function may also have nested blocks, in the form of things like the if-constructs and the while-constructs.

Example
The following program has a function, called fn:

#include <iostream>
using namespace std;


void fn(int ident)
    {
        cout << ident<<'\n';

        int var = 5;

        if (ident !=5)
            {
                cout << ident << " is not what we are looking for.\n";
                cout << var << " is what we are looking for.\n";
                int cent = 100;
            }
    }


int main()
    {

     fn(33);


    return 0;
}

There are actually two functions in the code. The function that interest us is the function called, fn. The function starts with the parentheses (prototype) part, followed by a block. The block has a nested block.

Any identifier such as, ident, declared in the function parentheses is seen in the function block and in the inner block. Such an identifier cannot be seen outside the function (block). Any identifier such as, var, declared in the function outer block, can be seen in the outer block, as well as in the inner block. Any identifier such as, cent, declared in the if-block inside the function block, can be seen only inside the if-block itself.

Member Function in Classes
A class can also have functions. Such functions are called methods or member functions. All the above rules apply to member functions.

As you can see, there is a lot of similarity between the function scope and the local scope. Local scope concerns, the if, the for, the while and the switch constructs. Function scope concerns ordinary functions and member functions.

Functions are very important in programming. There is no computer language that does not have functions. A pure OOP language like Java, would have methods instead of functions.

You still have to study the class scope and the namespace scope, in this series. When we get there, you will see that the different scopes in C++ are similar, with focus on the block.

Well, let us stop here and continue in the next part of the series.

Chrys

Related Courses

C++ Course
Relational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message