Functions and scope

The compiler will also take the scope of the function into account when looking for a suitable function. You cannot define a function within a function, but you can provide a function prototype within the scope of a function and the compiler will attempt (if necessary through conversions) to call a function with such a prototype first. Consider this code:

    void f(int i)    { /*does something*/ } 
void f(double d) { /*does something*/ }

int main()
{
void f(double d);
f(1);
return 0;
}

In this code, the function f is overloaded with one version that takes an int and the other with a double. Normally, if you call f(1) then the compiler will call the first version of the function. However, in main there is a prototype for the version that takes a double, and an int can be converted to a double with no loss of information. The prototype is in the same scope as the function call, so in this code the compiler will call the version that takes a double. This technique essentially hides the version with an int parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset