Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 288
Michi Kampl Avatar asked Sep 19 '13 09:09

Michi Kampl


People also ask

How do I return negative value in CPP?

According to the standard, the return value of main() is passed to std::exit(int) . From there, by C++11 § 18.5, "If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

Can we return negative value in C?

The answer to your question is yes; printf() in C will return a negative value if there's an encoding error, or if you redirect to an invalid handle.

Can INT take negative values in C++?

An int is signed by default, meaning it can represent both positive and negative values.

Can you have a negative double in C++?

There are no unsigned floating-point data types. On all machines, variables of the float, double, and long double data types can store positive or negative numbers.


2 Answers

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.

like image 167
Emilio Garavaglia Avatar answered Oct 08 '22 06:10

Emilio Garavaglia


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.

like image 36
nijansen Avatar answered Oct 08 '22 06:10

nijansen