Bash Question

C: main() returning an array always equals to 56

I wonder what happens when I play with the return value of the


I found that if I return an array variable from
(which is supposed to be the exit status) and print the exit status in shell, the output is always 56. I wonder why?

The C program:

int* main(void) {
static int x[3];
return x;

I test it as follows:

gcc array_return.c -o array_return
echo $?

The output is always
even if I change the size of the array, or change the numbers in it. What does the number

Answer Source

Your program returns a pointer. It's not an "array" as you put it in the question. Because the name of an array evaluates to the address of its first item (which is the same as address of the array itself).

In C, the value returned from the main function is interpreted as the exit status, i.e. the $? variable used in your example.

I guess, you're running Bash shell, since in Bash the exit status is stored in the $? variable. A pointer is usually a big number, at least bigger than 255, which is a maximum exit code in Bash:

Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225).

Now let's modify your program by printing the address of the variable, and the address modulo 256:

#include <stdio.h>

int main(void) {
    static int x[3];
    printf("%ld ==> %d\n", (size_t)x, (size_t)x % 256);
    return (int)x;

Let's compile it and test if I'm right:

$ gcc -Wall -g test.c -o test && ./test; echo $?
test.c: In function ‘main’:
test.c:6:12: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
     return (int)x;
6295620 ==> 68

As we can see, the return status is equal to 6295620 % 256, as it is documented in the official documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download