Redeclaring a function inside a function
c++
Solution
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 );
}
}
Problem
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?