Declaring function inside function in C

  • A+
Category:Languages

I found this question on an online exam. This is the code:

#include <stdio.h>  int main(void) {     int demo();     demo();     (*demo)();     return 0; }  int demo(){     printf("Morning"); } 

I saw the answer after the test. This is the answer:

MorningMorning 

I read the explanation, but can't understand why this is the answer. I mean, shouldn't the line int demo(); cause any "problem"?

Any explanation is helpful. Thanks.

 


It is not a problem because that int demo(); is not a function definition, it is just an external declaration, saying (declaring) that a function of such name exists.

In C you cannot define a nested function:

int main(void) {     int demo() {} //Error: nested function!!! } 

But you can declare a function just fine. It is actually equivalent to:

#include <stdio.h>  int demo(); //function declaration, not definition  int main(void) {     demo();     (*demo)();     return 0; }  int demo(){     printf("Morning"); } 

except that in your code the external forward demo() declaration is only visible inside main.

Comment

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