Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `return 0x1;` mean?

When browsing the source of a project on web I've found some return statement in main that looks weird to me:

int main()
{
    /* ... */
    return 0x1;
}

So main is returning 0x1 radix 16, but that's 1 radix 10! Shouldn't main return 0?

That is incorrect, right? By the way is it Okay to return 0x0?

like image 304
Rizo Avatar asked Oct 11 '10 07:10

Rizo


4 Answers

It returns 1. 0x1 Is just a hex value of 1.

You are free to return 0x0, too. It's just a different representation of 0. You could use octal, too, if you like :)

like image 161
JoshD Avatar answered Oct 06 '22 12:10

JoshD


0x1 or 1 makes no difference. It's the same number. Consequently, you can return 0x0 as well - it's just a different way of writing 0 in your code.

However, assuming that return is the last line of code in your main block, you're right that it should probably not be returning 1: non-zero return codes from main signify failure, and if the program runs to the end, that's generally a sign of success - so you should return 0 in that case.

However, it is entirely possible to structure a program the other way around, so it is therefore also possible that returning 1 is correct here.

like image 29
Michael Madsen Avatar answered Oct 06 '22 13:10

Michael Madsen


Simply put that translates to:

return 1;

by putting 0x in front of the number it allows you to enter Hexadecimal numbers into the source code e.g. 0xFF = 255

It's possible for your main function to return any value you want, this way you can effectively document any error conditions that may (or may not) have happened. If this program was called by a process that interrogates the return value, then if you change the return value to 0x0 (or just 0) then the calling program might change its behaviour unexpectedly.

like image 3
TK. Avatar answered Oct 06 '22 14:10

TK.


Yes, 0x1 (hexadecimal 1) is the same as 1 (decimal 1). So, the above is equivalent to plain return 1.

main is not required to return 0. main "should" return whatever its author wants it to return. They wanted to return 1 - they returned 1. They wanted to use hexadecimal notation - they used hexadecimal notation.

Someone just felt like doing it that way. There's no other explanation.

like image 2
AnT Avatar answered Oct 06 '22 13:10

AnT