Thursday, 14 August 2014

can we have same name for function and variable?

 
#include<cstdio>

void callme(int callme)
{
    printf("\n I was called!");
}

class test
{
    int main;
   
};


int main()
{
    int main;
    // float main; Gives error
    //test main; Gives error
   
    callme(4);
    return 0;
}

Do you think it gives error?

No it will not give compile error.

Do you think C++ is mad to allow like this?

Not so, The above statement is allowed because  function name main is in different scope and integer main is in different scope. But The following program gives the error

int main; // main occured 1st time in scope
int main() // Oh! main occured 2nd time in scope. Error
{
    int main;
    // float main; Gives error
    //test main; Gives error
   
    callme(4);
    return 0;
}

Here the 1st main (integer) and second main(function name) both in same scope. so it will give the error.

To better understood watch the following program.


#include<cstdio>


int main()
{
    int my_var;
    {
        int my_var;
        {
            int my_var;
            {
                int my_var;
            }
        }
    }
    printf("Hurray! No Compiler error")    ;
    return 0;
}