Search code examples
cfunctionoutputprogram-entry-point

Why does the program only give an output if defined in main (and how can I change this)?


I tried to run this

int array( void )
{
    char text[12] = {  112, 114, 111, 103, 112, 0 };
    int i;
    for(i = 0; text[i]; i = i +1)
        printf("%c", text[i]);
    printf("\n");
    return 0;
}

int main( void )
{
    int array(void);
    return 0;
}

and the program runs but I am getting no result. Now when I use the main function to define the program:

int main( void )
{
    char text[12] = {  112, 114, 111, 112, 0 };
    int i;
    for(i = 0; text[i]; i = i +1)
        printf("%c", text[i]);
    printf("\n");
    return 0;
}

I get the result progr(as wanted). I already searched but the only related questions I find are about using main as a function name and wrong outputs. Maybe I am searching the wrong way but I would be pleased if someone could answer this.


Solution

  • Your direct problem is that you did not call the function array, you declare it inside the body of main. The declaration itself does not execute the code.

    A function declaration tells the compiler about a function's name, return type, and parameters.

    A function definition provides the actual body of the function.

    Defining a Function

    The general form of a function definition in C programming language is as follows

    return_type function_name( parameter list ) {
       body of the function
    }
    

    In your case you have two function definitions:

    // 1.
    int array( void )
    {
        char text[12] = {  112, 114, 111, 103, 112, 0 };
        int i;
        for(i = 0; text[i]; i = i +1)
            printf("%c", text[i]);
        printf("\n");
        return 0;
    }
    
    // 2.
    int main(void)
    {
        //...
        return 0;
    }
    

    Function Declarations

    A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

    int array(void); // function declaration, no parameters, returns int value 
    

    Calling a Function

    To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.

    In your case call it like this:

     array();
    

    since there are no parameters to pass.

    To sum up:

    int array(void);   // function declaration, no parameters, returns int value 
    
    int array(void)    // definition of the function `array`
    {   
        // function body
        char text[12] = {  112, 114, 111, 103, 112, 0 };
        // ...
        return 0;
    }   
    
    int main(void)    // definition of the function `main`, 
    {
      array();        // function call, calling function `array` with no parameters
      return 0;
    }