3 ms·
> The order of the function definitions in the source code makes no difference to the program’s meaning. Not exactly true. Consider: #include <stdio.h>
by WalterBright 4y ago
> The order of the function definitions in the source code makes no difference to the program’s meaning.
Not exactly true. Consider:
#include <stdio.h>
int foo(double d) { return (int)d; }
int main() { printf("%d\n", foo(3)); return 0; }
/*int foo(double d) { return (int)d; }*/
This prints different results depending on whether `foo` is defined before `main` or after `main`. This is caused by implicit function declaration.
gcc will warn about this if the -std=c11 switch is thrown, but by default it will compile without error or warning.
- WalterBright 4y agoAmusingly, the ImportC compiler I wrote will produce the same result regardless of the order, because it allows forward references.
- marcodiego 4y agoHere gcc (9.4.0) throws a warning if the first declaration is commented and the second one uncommented, but it prints "0". Care to explain why?
- WalterBright 4y agoBecause foo() gets implicitly declared as accepting int arguments, when it actually accepts a double. The double bits interpreted as an int are 0.
- edflsafoiewq 4y agoOn x64, foo(double) expects its argument in xmm0, but foo(int) expects it in rdi. So the 3 passed in rdi is ignored and it operates on whatever happened to be in xmm0.
- WalterBright 4y agoYes, you're right. Thanks for the correction. I was thinking of the Windows C ABI.
- stephencanon 4y agoStrictly speaking he's correct as "definition" is distinct from "declaration", but yeah.
- WalterBright 4y agoI wrote definitions in the example, and the order dependence is clear.
- kragen 4y agoBut if you declare the foo function before main, it works correctly regardless of where it's defined. The definition just has the effect of also declaring it, which is what makes the difference. (Of course you know all this much better than I do, but someone younger reading this thread might be mystified.)
- WalterBright 4y agoThat wasn't the statement in the book, though. The thing is, this is a serious misfeature which isn't present in other languages, and can cause bizarre problems to the poor newbie user. This order dependency is why C source code tends to be written bottom-up, rather than the more natural top-down.
- kragen 4y agoAgreed on all four points.
- blinkingled 4y agogcc 12.2 on Arch warns about it with no switches - sure RMS did not put a disclaimer on his claim but one can reasonably assume he meant if you write correct C the order will not matter. (Btw I have a feeling every statement about C would need to carry that disclaimer lol - main will be called if you did not LD_PRELOAD a .so that caused premature exit in init function etc.) gcc /tmp/testf.c /tmp/testf.c: In function ‘main’: /tmp/testf.c:4:18: warning: implicit declaration of function ‘foo’ [-Wimplicit-function-declaration] 4 | printf("%d\n", foo(3)); | ^~~