In Linux for example when i use batch if error code is 0 thats good, but what is the convention in C++ ?
when int (or bool) is equal to one we say that's true, but what must be the return of such function in C++ ?
In Linux for example when i use batch if error code is 0 thats good, but what is the convention in C++ ?
when int (or bool) is equal to one we say that's true, but what must be the return of such function in C++ ?
A C++ function or method can return a bool
value like true
or false
. A program (i.e. the main
function) must return an int
value, for example 0
to report 'success'.
In C++ it is common to use boolean return to indicate true for success, and false for failure.
It is also common to use an integer return value where zero indicates success, and non-zero to indicate failure or any other condition (often negative numbers can indicate errors, while positive indicate some other outcome).
Whichever approach you choose, the important thing is to document it and be consistent throughout the code base.
Standard C functions that return an integer usually return greater-than or equal to zero for success and -1 for failure. When -1 is returned, errno
is usually set to provide a more specific error. Zero indicates a generic success where numbers greater than zero are assumed to be successful and provide additional detail.
Consider something like recvfrom()
. A return value of -1 indicates outright failure with errno
set to a detailed code. A return value of zero means that the socket was shutdown in an orderly fashion and that additional calls will not return data. A return value greater than zero means that data was received and the number of bytes received is what was returned.
In C and its runtime library 0 means success (sometimes polling errno is required).
In C++ world is more colourful:
DON'T mix bool usage convention and "0", result is just plain confusing code(see example). If you happen to need multiple values use enumeration, additional return parameter or exception depending on situation.
introduced bool and '0' code confusion:
// sorry for abuse of "C" for educational purposes
bool isSame(s1,s2) { return s1==s2; }
int isSame2(s1, s2) { return strcmp(s1.cstr(), s2.cstr()); }
if (isSame(..) && !isSame2(..)) ...
I understand you to be asking two questions:
Basic answers follow.
Typically the program (main()) returns 0 for success, and other values - errors - for failure
If a function can either succeed or fail, it is, typically, typed as bool and returns true or false.
If a function can return multiple values it will, typically, return int or enum values.
Try throwing exceptions for those cases which are exceptional.