skip to Main Content

Here are the simple programs in C that returns different values

program : 1

#include<stdio.h>

int main()
{
    printf("Hey I am returning the valuen");
    return 0;
}

program 2:

#include<stdio.h>

int main()
{
    printf("Hey I am returning the valuen");
    return 255;
}

program 3:


#include<stdio.h>

int main()
{
    printf("Hey I am returning the valuen");
    return 258;
}

When I examine the return value of C program after the execution of it using the command echo $? in ubuntu it gives me ,

for program 1 : 0

for program 2 : 255

for program 3 : 2

After the value 256 ,it again returns1 and so on…

Why this cycle happens?

2

Answers


  1. The return value of main() is equivalent to the status argument to exit(). The C specification only documents three values of the exit status:

    • EXIT_SUCCESS or 0 (which are typically the same), meaning that the program terminated successfully.
    • EXIT_FAILURE, meaning that the program ended unsuccessfully.

    The treatment of any other value is implementation-defined.

    POSIX further specifies that only the least significant 8 bits will be available to a waiting process. The wait() family of functions put this in the low-order 8 bits of the termination status, using the other bits to hold flags that can be accessed with macros such as WIFSIGNALED() (which indicates whether the process terminated due to receiving a signal rather than calling exit()).

    Login or Signup to reply.
  2. Because traditionally many operating systems and C implementations used a single byte (8 bits) to store the exit status of a process, the range 0 to 255 is frequently referenced. Since a single byte can store values in the range of 0 to 255 (28 – 1), this range came to be widely accepted as the standard for expressing exit statuses.

    The exit status is still expressed using a single byte in contemporary systems, particularly those based on Unix-like operating systems. The return value range from main() is not subject to any specific restrictions, nevertheless, according to C, as it returns int. The operating system and runtime environment must determine how to interpret the return value and manage it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search