Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function calls: Understanding the "implicit int" rule

Tags:

c

function

If "a function" were compiled separately, the mismatch would not be detected, "the function" would return a double that main would treat as an int... In the light of what we have said about how declarations must match definitions this might seems surprising. The reason a mismatch can happen is that if there is no function prototype, a function is implicitly declared by its first appearance in an expression, such as

    sum += "the function"(line);

If a name that has not been previously declared occurs in an expression and is followed by a left parenthesis, it is declared by context to be a function name, the function is assumed to return an int, and nothing is assumed about its arguments.

I apologize beforehand for the ambiguous question, but what does this mean?

By the way this is page 73 chapter 4.3 from Brian W. Kernighan and Dennis M. Ritchie's C Programming Language book, 2nd edition.

like image 916
Matthew Hoggan Avatar asked Nov 22 '11 00:11

Matthew Hoggan


Video Answer


1 Answers

K&R2 covers the 1989/1990 version of the language. The current ISO C standard, published in 1999 2011, drops the "implicit int" rule, and requires a visible declaration for any function you call. Compilers don't necessarily enforce this by default, but you should be able to request more stringent warnings -- and you definitely should. In well-written new code, the rule is irrelevant (but it is necessary to understand it).

An example: the standard sqrt() function is declared in <math.h>:

double sqrt(double);

If you write a call without the required #include <math.h>:

double x = 64.0;
double y = sqrt(x);

a C90 compiler will assume that sqrt returns int -- and it will generate code to convert the result from int to double. The result will be garbage, or perhaps a crash.

(You could manually declare sqrt yourself, but that's the wrong solution.)

So don't do that. Always include whatever header is required for any function you call. You might get away with calling an undeclared function if it does return int (and if your compiler doesn't enforce strict C99 or C11 semantics, and if a few other conditions are satisfied), but there's no good reason to do so.

Understanding the "implicit int" rule is still useful for understanding the behavior of old or poorly written code, but you should never depend on it in new code.

like image 70
Keith Thompson Avatar answered Nov 09 '22 13:11

Keith Thompson