How does C exactly run?

  • A+
Category:Languages

I just realized when I define a function in C and use it, I can either use it and define the function later or define it and use it later. For example,

int mult (int x, int y) {   return x * y; }  int main() {   int x;   int y;   scanf( "%d", &x );   scanf( "%d", &y );   printf( "The product of your two numbers is %d/n", mult( x, y ) ); } 

and

int main()     {       int x;       int y;       scanf( "%d", &x );       scanf( "%d", &y );       printf( "The product of your two numbers is %d/n", mult( x, y ) );     }     int mult (int x, int y)     {       return x * y;     } 

will both run just fine. However, in Python, the second code will fail since it requires mult(x,y) to be defined before you can use it and Python executes from top to bottom(as far as I know). Obviously, that can't be the case in C since the second one runs just fine. So how does C code actually flow?

 


Well, the second code is not valid C, strictly speaking.

It uses your compiler's flexibility to allow an implicit declaration of a function, which has been disallowed in C standard.

The C11 standatd explicitly mentions the exclusion in the "Foreword",

  1. Major changes in the second edition included:

...

  • remove implicit function declaration

You have to either

  • Forward declare the function.
  • Define the function before it's usage (like snippet 1).

Enable the warning in your compiler and your compiler should produce some warning message to let you know about this problem.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: