Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 732
Gottaquest Avatar asked Jan 02 '23 15:01

Gottaquest


1 Answers

Since the function returns int, You should've assigned its return value to int too. OR
You can just call it normally with only its name because it always returns a 0 constant.

int i = array(); // i = 0
// or
array();

It's just printing and its value is always 0.
Then I suggest making it void instead because You'll need to call it by name only.

#include <stdio.h>
void array()
{
    char text[12] = {  112, 114, 111, 103, 112, 0 };
    for(int i = 0; text[i]; i++)
        printf("%c", text[i]);
    printf("\n");
}
int main()
{
    array();
    return 0;
}

Note that You can't assign the type void to anything.

like image 119
Beyondo Avatar answered Jan 05 '23 17:01

Beyondo