Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop runs with an undefined function's name as a condition

Tags:

c

gcc

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?

like image 967
Divyansh_C Avatar asked Jan 26 '23 10:01

Divyansh_C


1 Answers

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 as if (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 use strcmp. This warning is enabled by -Wall.

like image 146
Sourav Ghosh Avatar answered Jan 29 '23 13:01

Sourav Ghosh