I stumbled over an interesting question in a forum a long time ago and I want to know the answer.
Consider the following C function:
f1.c
#include <stdbool.h>
bool f1()
{
int var1 = 1000;
int var2 = 2000;
int var3 = var1 + var2;
return (var3 == 0) ? true : false;
}
This should always return false
since var3 == 3000
. The main
function looks like this:
main.c
#include <stdio.h>
#include <stdbool.h>
int main()
{
printf( f1() == true ? "true\n" : "false\n");
if( f1() )
{
printf("executed\n");
}
return 0;
}
Since f1()
should always return false
, one would expect the program to print only one false to the screen. But after compiling and running it, executed is also displayed:
$ gcc main.c f1.c -o test
$ ./test
false
executed
Why is that? Does this code have some sort of undefined behavior?
Note: I compiled it with gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2
.
f1()
into the same file asmain()
, you'd get some weirdness: While it is correct in C++ to use()
for an empty parameter list, in C that is used for a function with a not-yet-defined parameter list (it basically expects a K&R-style parameter list after the)
). To be correct C, you should change your code tobool f1(void)
. – uliwitnessmain()
could be simplified toint main() { puts(f1() == true ? "true" : "false"); puts(f1() ? "true" : "false"); return 0; }
– this would show the discrepancy better. – Palecvoid
? – Ho1true
andfalse
in K&R 1st ed., so there were not such problems at all. It was just 0 and non-zero for true and false. Isn't it? I don't know if prototypes were available at that time. – Ho1_Bool
type and no<stdbool.h>
header. – Jonathan Leffler