...
C no longer allows the absence of type specifiers in a declaration. Subclause 6.7.2 of the C Standard [ISO/IEC 9899:2011] states:
At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each
struct
declaration and type name.
...
However, to conform with the C Standard, you must explicitly prototype every function before invoking it. An implementation that conforms to the C Standard may or may not perform implicit function declarations. However, C does require the implementation to issue a diagnostic if it encounters an undeclared function being used.
In the following this noncompliant code example, if malloc()
is not declared, either explicitly or by including stdlib.h
, a compiler that only complies with C90 may implicitly declare malloc()
as int malloc()
. (Compilers that comply only with C90 are required to provide an implicit declaration of malloc()
. ) If the platform's size of int
is 32 bits, but the size of pointers is 64 bits, the resulting pointer could would likely be truncated as a result of the implicit declaration of malloc()
returning a 32-bit integer.
Code Block | ||||
---|---|---|---|---|
| ||||
/* #include <stdlib.h> is missing */ int main(void) { size_t i; for (i = 0; i < 100; ++i) { char *ptr = (char*)malloc(0x10000000); /* int malloc() assumed */ *ptr = 'a'; } return 0; } |
When compiled with Microsoft Visual Studio (a C90-only platform), the preceding this noncompliant code example will eventually cause an access violation when dereferencing ptr
in the loop.
...
Noncompliant Code Example (Implicit Return Type)
Similarly, do Do not declare a function with implicit return type. If it returns For example, if a function returns a meaningful integer value, declare it int
. If it returns no meaningful value, declare it void
.
...
Because the compiler assumes that foo()
returns a value of type int
for this noncompliant code example, UINT_MAX
is incorrectly converted to −1.
...
This compliant solution explicitly defines the return type of foo()
as unsigned int
:. As a result, the function correctly returns
UINT_MAX
.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> #include <stdio.h> unsigned int foo(void) { return UINT_MAX; } int main(void) { long long c = foo(); printf("%lld\n", c); return 0; } |
Risk Assessment
Occurrences of an omitted type specifier in existing code are rare, and the consequences are generally minor, perhaps resulting in abnormal program termination.
...