Why does this code run?
#include <stdio.h>
int i();
int main(){
while(i){printf("Hi");}
}
What exactly is the value of i that the while loop accepts?
I tried printf("%d", i)
and it said that i
is undefined which was expected since it has only declaration, but why does while
work?
If you compile with proper warnings enabled, you'll see
warning: the address of ‘i’ will always evaluate as ‘true’ [-Waddress]
while(i){printf("Hi\n");}
Here, the value of i
is taken as the address of the function, i.e., the function pointer.
To add a bit more context, from gcc manual (emphasis mine)
-Waddress
Warn about suspicious uses of memory addresses. These include using the address of a function in a conditional expression, such as
void func(void); if (func)
, and comparisons against the memory address of a string literal, such asif (x == "abc")
. Such uses typically indicate a programmer error: the address of a function always evaluates to true, so their use in a conditional usually indicate that the programmer forgot the parentheses in a function call; and comparisons against string literals result in unspecified behavior and are not portable in C, so they usually indicate that the programmer intended to usestrcmp
. This warning is enabled by-Wall
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With