Search code examples
cfunctionfunction-pointersfunction-declaration

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.


Solution

  • 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.