Click here to Skip to main content
15,880,956 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I am checking to see if a function worked as it should, I usually do it this way :
C++
int result;

result = SomeFunc();

if(result)
{
   //someFunc() returned a non-zero value which means it worked with no errors
}
else
{
   //someFunc() returned 0. Something is wrong.
}


What I am asking is that, when I declared the variable result, is it guaranteed to be equal to zero ? Is this a good practice ? If not, How shall I do this ?

Assume for some reason the following isn't possible, because it is necessary to store the return value of SomeFunc.

C++
if(SomeFunc())
{
}
else
{
}


Thanks in advance.
Posted

If an integer is not initialized, its value is undefined.

But in your approach, you no need to worry about the initial value as you are returning 0 or some other number according to your logic. So, the following logic of yours is correct.
C++
int result = SomeFunc();
 
Share this answer
 
v2
Comments
Codexzy 29-Dec-13 1:06am    
Thank you.
Most welcome. :)
H.Brydon 29-Dec-13 11:21am    
... except that I hate seeing uninitialized values - anywhere. My preference would be to combine the two statements into one:

int result = SomeFunc();
Oh yes, that would be more awesome. Let me update my answer.

Thanks,
Tadit
Quote:
when I declared the variable result, is it guaranteed to be equal to zero ?

When you declare it, it's not guaranteed to be anything. You should initialize if you want it to be guaranteed to be equal to something. As far as what it will be when the function returns, well that'll be function specific. Most functions use a returned zero as success, because then they can use the returned number as an enumerator to a list of error codes.

As an example, see how MS treats error codes (0=ERROR_SUCCESS, operation completed successfully):
http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx[^]

Quote:
Is this a good practice ?

Sure, as long as you know exactly what it is that the function is returning and you're checking the return condition correctly. In your code you're assuming 0 is error state, you'll have to know that to be true for the function you're calling, which as I've mentioned, is opposite of what most people do.
 
Share this answer
 
Comments
Codexzy 29-Dec-13 1:06am    
Thank You. Very informative.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900