C++: How can I return a negative value in main.cpp

扶醉桌前 提交于 2019-11-29 05:52:21

问题


As an assignment in school, we have to write a C++ program and returns different error codes in the main.

The problem is that we have to return -2 if a specific error occurs but I have no idea how to return a negative value.

For example:

int main()
{ 
    int a = -2; 
    return a;
}

In windows this gives me a return value like: 42232684 and in Linux there is: 253

Why -2 is not allowed?

And how can I manage to get -2?


回答1:


The problem is that what is returned to the OS is then interpreted by the OS shell as IT likes it, not as your program likes.

the main function returns an int, and return -2 is just what your program has to do.

253 is -2 in 2s complement onto 8 bits.

The problem -here- is a mismatch between the C++ specs (int main()) and the way the shell use it. But it does not depend on the program.

The assignment itself is a trap.




回答2:


From C++11 standard 18.5/8:

If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Thus is it completely compliant that you get different results for different platforms, and/or compilers.




回答3:


Unix, and linux are limited to 8 bit return codes, -2 is 0xfe. Which your shell will understand to be 254 when you echo $?

You're expected to give a return code between 0 and 255.

http://en.wikipedia.org/wiki/Exit_status

on POSIX-compatible exit statuses are restricted to values 0-255, the range of an unsigned 8-bit integer.



来源:https://stackoverflow.com/questions/18890534/c-how-can-i-return-a-negative-value-in-main-cpp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!