Swann
Swann

Reputation: 2473

Return negative value in main in C

Hello StackOverflow community.

I am actually working on a project trying to emulate a very basic shell. I have an exit builtin that take a parameter and based on this I need to return the correct value (value % 256)

For example :
exit 42 will return 42 exit 300 will return 44

But I can't find exactly how this is exactly working is someone was trying to do exit -30 for example. I did some test and found out it was 226 beside the fact that it's 256 - 30 where it comes from ?

Upvotes: 1

Views: 9258

Answers (4)

Kevin
Kevin

Reputation: 2182

Your program is returning an unsigned int. Since the number has to be positive, the calculated value from the modulus ends up looking like the numbers 'wrapped around'.

Here is some quick test code to demonstrate:

int main(){
    unsigned int x = -30;
    signed int y = -30;
    printf("%d\n", x % 256);
    printf("%d\n", y % 256);
}

Output:

226
-30

Upvotes: 3

Arkku
Arkku

Reputation: 42149

C standard leaves most things about the return values of main to be defined by the implementation. Basically returning 0, EXIT_SUCCESS, or EXIT_FAILURE is somehow standard and reliable, everything else depends on the platform. In this case it seems like the operating system gives you the value modulo 256 (as an uint8_t).

Upvotes: 4

honzajscz
honzajscz

Reputation: 3107

Modulo is always a positive number in the programming languages and besides here is a something on returing negative numbers from main to OS C++: How can I return a negative value in main.cpp

Upvotes: 0

HelloWorld123456789
HelloWorld123456789

Reputation: 5369

Return values of a program to the linux kernel are of uint8_t type.

Upvotes: 1

Related Questions