Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absurd compilation

Tags:

c

This is a basic C code, which according to me should have thrown three errors (function not defined, function not returning anything, function argument missing). But to my surprise it threw nothing, it compiled and gave some garbage results:

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])
{
    int a=f1();
    printf("a %d\n",a);
    system("PAUSE");    
    return 0;
}


f1(int *t)
{
       printf("t %d", t);
}

PS: I am using a gcc compiler on windows.

like image 411
Nik Avatar asked May 24 '26 12:05

Nik


1 Answers

In C when a function is not declared is is assumed to return int and compilation continues (btw this can lead to nasty bugs). If the function is declared without a type (as f1() is in your code it is assumed to return int. Not returning a value from a non-void function (as in your code) is undefined behavior.

So none of the points you mention are required to cause a compilation error. Undefined behavior is not required to prevent your program from running - the program might run and might even produce good looking results.

like image 144
sharptooth Avatar answered May 27 '26 06:05

sharptooth