1

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 ?

Swann
  • 2,413
  • 2
  • 20
  • 28
  • 1
    umm... it's `-30 % 256 = 226` – bolov Feb 27 '14 at 19:48
  • Yeah I know but I read that there is different ways of interpreting modulo with negative number. But I wanted to understand the meaning behind it, I am also not sure if it's better to exit() or return() in a main. – Swann Feb 27 '14 at 20:02

4 Answers4

4

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).

Arkku
  • 41,011
  • 10
  • 62
  • 84
3

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
Kevin
  • 2,112
  • 14
  • 15
1

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

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
0

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

Community
  • 1
  • 1
honzajscz
  • 2,850
  • 1
  • 27
  • 29