Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring function inside function in C

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.

like image 240
Debanik Dawn Avatar asked Dec 18 '22 22:12

Debanik Dawn


2 Answers

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.

like image 162
rodrigo Avatar answered Dec 20 '22 12:12

rodrigo


You can declare a function inside another function. This is allowed. The only thing is it is visible only inside the function in which it is declared.

like image 39
H.S. Avatar answered Dec 20 '22 11:12

H.S.