Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redeclaring a function inside a function

Tags:

c++

I stumbled across a strange c++ snippet. I consider this as bad code. Why would someone repeat the function declaration inside a function? It even compiles when changing the type signature to unsigned int sum(int, int) producing the expected result 4294967294j. Why does this even compile?

#include <iostream>
#include <typeinfo>

using namespace std;

int sum(int a, int b){
    return a + b;
}

int main()
{
    int sum(int, int); // redeclaring sum???
    int a = -1;
    auto result = sum(a, a);
    cout << result << typeid(result).name() << endl;
}

Edit: It compiles for me... but is it valid C++ code? If not why does the compiler (mingw 4.8.1) allow it?

like image 624
Markus Avatar asked Feb 14 '14 14:02

Markus


1 Answers

Sometimes there is a sense to redeclare a function inside a block scope. For example if you want to set a default argument. Consider the following code

#include <typeinfo>

using namespace std;

int sum(int a, int b){
    return a + b;
}

int main()
{
    int sum(int, int = -1 ); // redeclaring sum???
    int a = -1;
    auto result = sum(a, a);
    cout << result << typeid(result).name() << endl;

    result = sum(a);
    cout << result << typeid(result).name() << endl;
}

Another case is when you want to call a concrete function from a set of overloaded functions. Consider the following example

#include <iostream>

void g( int ) { std::cout << "g( int )" << std::endl; }
void g( short ) { std::cout << "g( short )" << std::endl; }

int main()
{
   char c = 'c';
   g( c );

   {
      void g( short );
      g( c );
   }
}
like image 126
Vlad from Moscow Avatar answered Oct 12 '22 01:10

Vlad from Moscow