is check required in this situation - c++

In C++ I read a coding guideline as "check return value in If control statement"
Like,
if(TRUE == fun1())
{
//Statements
}
When "fun1" returns True, internally in "if" statement it will be compared with “true”.
Is it necessary to compare externally.?
Is this a good practice or is this style of coding decreases performance.?

Comparing to TRUE is never a good idea.
If fun1 returns a BOOL, than its value is in fact an int and can have any int value. TRUE is just 1, FALSE is 0. But there are a lot of other values for an int. Comparing to FALSE is always save!
In a lot of cases. Functions return "something" and that should mean "TRUE" (!=0) as long as it is different from 0!
As long as you have a bool return value you can compare to true and false and it will always work.
It depends on the style, but I never use an expression to compare to a TRUE value (meaning not 0, not false). I always write the condition without an operator in the if statement. And it has the meaning for me "If fun1 is something" or "If fun1 succeeded"
if (fun1())
{
//Statements
}
In our company this is the normal coding style. And if we want to check the reverse. "If fun1 fails"
if (!fun1())
{
}
With modern compilers and processors there is no real speed impact.

Depends on the return type of fun1 and the type of TRUE.
If TRUE is true and fun1 returns bool, it doesn't decrease performance, because it does exactly what the if does itself. So it's just no-op clutter.
With other types, it looks dangerous and could even be wrong. Imagine a legacy-style function which returns int and is documented to return 0 on failure and a non-zero value on success (quite a few C standard library functions are like that). Then, let's say TRUE is true or 1. In this case, the function returning 2 (a perfectly valid non-zero value) would actually fail the condition!
So unless the types and values are so perverted that TRUE is 0 (which is not the case with MFC), I'd say it's actually harmful to compare with it.

Related

Why does bool exist when we can use int?

This may sound as a really dumb question. But it has been bothering me for the past few days. And It's not only concerning the C++ Programming Language as I've added it's tag. My Question is that. In Computer Science Boolean (bool) datatype has only two possible values. 'true' or 'false'. And also, in Computer Science, 1 is true and 0 is false. So why does boolean exists at all? Why not we use an integer that can return only two possible values, Such as 1 or 0.
For example :
bool mindExplosion = true; // true!
int mindExplosion = 1; // true!!
// or we can '#define true 1' and it's the same right?
What am I missing?
Why does bool exist when we can use int?
Well, you don't need something as large as an int to represent two states so it makes sense to allow for a smaller type to save space
Why not we use an integer that can return only two possible values, Such as 1 or 0.
That is exactly what bool is. It is an unsigned integer type that represents true (1) or false (0).
Another nice thing about having a specific type for this is that it express intent without any need for documentation. If we had a function like (warning, very contrived example)
void output(T const & val, bool log)
It is easy to see that log is an option and if we pass false it wont log. If it were instead
void output(T const & val, int log)
Then we aren't sure what it does. Is it asking for a log level? A flag on whether to log or not? Something else?
What am I missing?
Expressiveness.
When a variable is declared int it might be used only for 0 and 1, or it might hold anything from INT_MIN..INT_MAX.
When a variable is declared bool, it is made explicit that it is to hold a true / false value.
Among other things, this allows the compiler to toss warnings when an int is used in places where you really want a bool, or attempt to store a 2 in a bool. The compiler is your friend; give it all the hints possible so it can tell you when your code starts looking funky.

Is there any significance to this return statement?

I was wondering if there was any significance in a part of a code I am seeing that involves
return (num!=0);
where num is an int. And this is the return statement of a boolean function that wants to return TRUE if num != 0, and false if num = 0.
I am not sure if there is an hidden significance to this, but I am not seeing why they cannot just simply write:
return num;
Here is the code I saw:
bool SemClass::cut(int &a, int &b, int &c)
{
int num = 0;
check(a, num);
check(b, num );
check(c, num);
return (num != 0);
}
The value 0 for integral, floating-point, and unscoped enumeration and the null pointer and the null pointer-to-member values become false when returned as a boolean by implicit conversion. Other values such as 1, 2, 3, 4 etc. map to true. This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
Implicit conversions: en.cppreference.com/w/cpp/language/implicit_cast
In this case, in C++, writing num and num!=0 are both fine. However, num!=0 might make it more obvious that the method is returning a boolean. Technically, only an integer of value 0 would equate to a boolean false, while all other values would equate to a boolean true. By writing num!=0, It is made explicit that the method would return true if num is not equivalent to 0 and false if it is.
Good practice dictates that if it's a genuine truth value, then you should use a boolean as it makes it very clear to the caller what will be returned. When returning an integer, it could be seen as a code/enum type value.
Therefore, num!= is preferred to num in this case. The brackets are not required however. Some compilers will also issue a warning if you return an integer when the method is supposed to return a boolean.
The author may have written return num, the compiler would generate the exact same binary. Here, the author tries to be explicit and to make as easy as possible to the reader to guess what the function returns.
When a quick reader sees return num knowing that num is an int and the current function returns a bool, (s)he needs to stop for a fraction of a second to a few seconds (depending on its concentration and ease regarding C++) to remember that an integer is implicitly convertible to a boolean with the mapping 0 -> false, anything else -> true. So, why not write that down?
When the quick reader sees return num!=0, (s)he guesses that the current function returns a boolean (it could be otherwise, but it would be suspicious) and comprehend easily what the return value means.
As a rule of thumb, I'd advise to pick the more explicit writing when it does not hurt the reading and when it takes only a few more (or less) characters. Don't forget that you do not write code for the compiler, you write code for the dozens of other developers who works or will work with you(r code). C++ may be less common in 20 years, it would be great if your program could be easily understood not only by gurus but by everyone (I'm generalizing there, not only talking about the implicit boolean conversion).
The author is being (excessively) careful on two counts:
The parentheses are redundant.
Any numeric type in C++ has an implicit conversion to bool: if the number compares to zero then it's false, else it's true.
Personally I prefer the naked return num; as I find that clearer.
(Note that in C, the relational operators return the int types 1 and 0, rather than true and false).

not able to understand return statement in isEmpty function of stack implementation

I have isEmpty() function in my stack. And it looks something like below.
bool Mystack<T>::isEmpty() const //function 1
{
if(top==-1)
return true;
else
return false;
}
I saw a couple of online code for isEmpty(), which I could not understand. Below is the snippet.
bool Mystack<T>::isEmpty() const //function 2
{
return top == -1;
}
Question 1: Are both the functions doing the exactly the same task?
Question 2: If yes, then can some one please explain how the syntax in function 2 performing its task without using any if statement.
top == -1 is an expression. Assuming no operator overloads are involved, its return type is bool. It will have the value true if top equals -1 and the value false if that's not the case.
return top == -1; means "return the value of the expression top == -1". As I've shown above, this value is either true or false. These coincide exactly with the values returned from the if()-based code, so the two codes are equivalent.
In my code, I tend to use parentheses around "syntactically unusual" return statements, and I consider == one of them. So I would write this in my code (and I would certainly prefer it to the if version):
return (top == -1);
Yes, both functions work exactly the same. They return whether top equals -1.
In the first code, this is written somewhat "explicitly" (from the reader's perspective). Its English equivalent would be (roughly):
Evaluate the expression top == -1.
If the result is true, then return true, else return false.
The second code does it more subtly, and its rough English equivalent would be:
Return the result of the expression top == -1.
Yes, they do exactly the same thing.
Think about the semantics of an if statement. The condition evaluates to a bool and is checked against true. top==-1 will either evaluate to true or false, if it evaluates to true then the first form is executed and true is returned, otherwise the second form is evaluated and false is returned. This is exactly the same as the second version, just more verbose.
Answer 1: Yes, same task.
Answer 2: I have no exact idea of c++, but logically
return top == -1;
can be broken into
check if the value of top is equal to 1 or not.
1.1 if equal, return 1 [or TRUE] (as a result of comparison success)
1.2 if not, return 0 [or FALSE] (as a result of comparison failure)
As reference, from C99 standard document, chapter 6.8.6.4, paragraph 3,
If a return statement with an expression is executed, the value of the expression is
returned to the caller as the value of the function call expression.
and for that of c++11, chapter 6.6.3, paragraph 2,
. . . A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function....

WINAPI methods with nonzero return value at success

For a lot of WINAPI methods, the return value is either 0 (failure) or nonzero (success). For example:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682565(v=vs.85).aspx
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero.
My question is, for such a method, is it correct to test the return value with TRUE (which is a BOOL value equal to 1)? Or is it more correct to test if the return value is !FALSE instead?
Another nonrelated question is, when the return value is non-zero, what exactly is it? Can it be any value or from a set of values?
The signature of the method you mentioned is:
BOOL WINAPI DeleteTimerQueue(_In_ HANDLE TimerQueue);
In the Windows headers the type BOOL is defined as an int. This is for historical reasons, since in the days before C99 there was no bool type that we are now familiar with, and WinAPI have kept using the BOOL definition for many of the methods introduced later on.
Further, the Windows headers look very similar to this, if we take the liberty to simplify a bit,
typedef int BOOL
#define FALSE 0 // < note that #define <number> introduces an integer constant
#define TRUE 1
Thus your question can be interpreted as whether testing for !<integer> is equivalent to testing against a boolean value. The answer is yes, with C++ testing !0 == true and !n == false for any integral n > 0.
Another nonrelated question is, when the return value is non-zero, what exactly is it? Can it be any value or from a set of values?
It will be different for different WinAPI methods. Generally it can be any value, but since the return type is conceptually a boolean, it is okay to test it as a boolean.
so to sum up I should check it as …
The idiomatic way to check is:
if(!DeleteTimerQueue(handle)) {
/* handle the error case */
/* call GetLastError() where applicable */
}
/* otherwise proceed, the call succeeded */

passing a flag in the form of "int" or a "bool" to a function, is better in terms of performance?

Say, I have a function like shown below
void caller()
{
int flag = _getFlagFromConfig();
//this is a flag, which according to the implementation
//is supposed to have only two values, 0 and 1 (as of now)
callee_1(flag);
callee_2(1 == flag);
}
void callee_1(int flag)
{
if (1 == flag)
{
//do operation X
}
}
void callee_2(bool flag)
{
if (flag)
{
//do operation X
}
}
Which of the callee functions will be a better implementation?
I have gone through this link and I'm pretty convinced that there is not much of a performance impact by taking bool for comparison in an if-condition. But in my case, I have the flag as an integer. In this case, is it worth going for the second callee?
It won't make any difference in terms of performance, however in terms of readability if there are only 2 values then a bool makes more sense. Especially if you name your flag something sensible like isFlagSet.
In terms of efficiency, they should be the same.
Note however that they don't do the same thing - you can pass something other than 1 to the first function, and the condition will evaluate to false even if the parameter is not itself false. The extra comparison could account for some overhead, probably not.
So let's assume the following case:
void callee_1(int flag)
{
if (flag)
{
//do operation X
}
}
void callee_2(bool flag)
{
if (flag)
{
//do operation X
}
}
In this case, technically the first variant would be faster, since bool values aren't checked directly for true or false, but promoted to a word-sized type and then checked for 0. Although the assembly generated might be the same, the processor theoretically does more work on the bool option.
If the value or argument is being used as a boolean, declare it bool.
The probability of it making any difference in performance is almost 0,
and the use of bool documents your intent, both to the reader and to
the compiler.
Also, if you have an int which is being used as a flag (due to an
existing interface): either use the implicit conversion (if the
interface documents it as a boolean), or compare it with 0 (not with
1). This is conform with the older definitions of how int served as
a boolean (before the days when C++ had bool).
One case where the difference between bool and int results in different (optimized) asm is the negation operator ("!").
For "!b", If b is a bool, the compiler can assume that the integer value is either 1 or 0, and the negation can thus be a simple "b XOR 1". OTOH, if b is an integer, the compiler, barring data-flow analysis, must assume that the variable may contain any integer value, and thus to implement the negation it must generate code such as
(b != 0) ? 0: 1
That being said, code where negation is a performance-critical operation is quite rare, I'm sure.