Why are function declaration mandatory in C++ and not in C?

Function declarations in C are not mandatory for legacy / backwards compatability reasons - if they were made mandatory then some old / legacy code somewhere would stop compiling.

I'd guess that they are mandatory in C++ becasuse C++ isn't a strict superset of C and so can make the sensible choice of making them mandatory.

You should always declare them however - see this question Must declare function prototype in C?

FYI in C99 function declarations are now mandatory.


In a discussion that involves both C and C++ "function declaration" is a rather vague term. These languages are significantly different in this regard.

In C++ language there's only one kind of function declaration: declaration with all parameter types and return type. Such declarations are necessary because C++ language supports function overloading. In order to choose which function to call the compiler needs to know everything about the function and needs to know which overloaded versions of the function are available. If you "forget" to declare some overloaded version, it will not be considered by overload resolution. That is at least one of the reasons function declarations are necessary in C++.

In C language there are two kinds of function declarations: non-prototype declarations and prototype declarations (or simply prototypes). A prototype in C is pretty similar to C++ declaration - it includes all parameter types. Prototypes have always been required in standard C for variadic functions (functions with ... parameters). For non-variadic functions prototype declarations are not required even today. But starting from C99 at least non-prototype declarations are required for all other functions. In older C89/90 version of the language function declarations for non-variadic functions were not required.

So, that should basically answer your question. In C++ function declarations are required because language features rely on them critically. In modern C function declarations are also required just to make the code safer. In older versions of C function declarations were not required mostly simply because the language was defined to work without them.

Tags:

C++

C

Declaration