Why does a false statement still execute? - c++

I have this code...
void drawMap(void)
{
if (false)
return;
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}
If I'm not mistaken it should NEVER execute...but it does...and when I change
if (false)
return;
to
if (false)
return;
else
return;
it doesn't execute at all now, but how can that first statement NOT be false? grabs headache pills
P.S. I only did this 'cause I was debugging and noticed my code was drawing to the screen when it wasn't supposed to.

if (false) will never execute its body... because the value of the condition is never true. So in the code you've given, the remainder of drawMap will always execute because it will never return at the start.
Consider if (x == 5) - that will only execute if the expression x == 5 is true. Now substitute false for x == 5...
If you want an if statement which will always execute, you want
if (true)
instead.

Count me in with the crowd that didn't actually read the problem well enough, or couldn't believe that the OP didn't understand the problem if it were so simple :)
John Skeet's answer, of course, was spot on :)
Two thoughts:
If you're in a debugger, lines can appear to be executed, out of order, not at all or at unexpected lines when compiled with optimizations. This is because some machine instructions will get 'attributed' to different source lines. Compile without optimization to eliminate the source of confusion. It is confusing only, as optimizations should (! barring compiler bugs) not alter effective behaviour
It could be that you're getting an evil #define for false that you cannot trust. Rule this out by running the code through preprocessor only. g++ -E will do that. MSVC++ has an option to 'keep preprocessed' source
Blockquote

if (false)
is analagous to
if (1 == 2)
and will therefore never execute the next statement (or block).
In your context consider the following comments I made:
void drawMap(void)
{
if (false) return; //Not gonna happen.
//The following will always happen
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}

I have seen the usage of this if(false), in a switch / case like construction like this:
int ret = doSomeThingFunction();
if (false) {}
else if (ret < 0 ) {
}
else if (ret == 0) {
}
else if (ret > 0) {
}

Related

Is it good practice if container's size is validated and accessing an element under same conditional statement?

Which one of the following code is more preferable between two of them and why?
1.
std::stack<int>stk;
//Do something
if( stk.empty() == true || stk.top() < 10 )
{
//Do something.
}
or
2
std::stack<int>stk;
//Do something
if( stk.empty() == true )
{
//Do something.
}
else if( stk.top() < 10 )
{
//Do something.
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first). So, expression stk.empty() || stk.top() < 10 is safe and good practice, stk.top() is only called if stk.empty() evaluates to false. In other words, the operators were designed to enable such usage.
It entirely depends on the use case. In the first code, you have an OR condition for empty stack and checking the value of element if an element exist. So, it's clear and you can proceed with the code.
In the 2nd code, you want to execute something different for both the conditions. Hence you have put the conditions in a if else loop.
Good practise comes into sense when you don't want your code to break or pass corner test cases.You might not wan't something in your code when the stack is empty.
std::stack<int>stk;
if(stk.top() < 10 )
{
//Do something.
}
else if(stk.empty() == true)
{
//Do something
}
This will generate run time error since the stack is empty but you are accessing top element before checking the stack empty condition.
Snap of the error
I hope the answer makes it clear.

Optimized code for two string compare in if condition

I want to do two string compare and used two different if condition. Is there any better way to do string compare in one if condition
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
}
The equivalent code is:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
Note: The compiler should generate the same machine code for both code samples. The difference is cosmetic and primarily aimed at the reader of the code.
You do get a difference when you add else clauses:
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
else
{
// else 1
}
}
else
{
// else 2
}
Compared to:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
else
{
// Single else clause
}
In addition to Klas's answer(just in case you're not familiar with the AND operator) - the AND operator ('&&') checks the first condition and it continues to check the second condition -only if- the first condition is true.
So in your specific question, it checks if the first couple of strings are equal and only if true (are equal), it checks if the second couple are also equal.
The obvious optimization (not mentioned yet), if you know anything about those strings, is to first perform the compare that is more likely to fail.

Should conditions test for positive or negative results?

Sorry if the title is rather ambiguous, I was not sure how to word it.
Is it better to phrase a condition such that the outcome you don't want enters the if statement then you exit the function or should I test for the outcome I do want and follow the statement with my code.
Maybe some examples would help:
What I mean by testing for negative result:
if(myObject == null) {
return;
}
//do whatever with myObject
What I mean by testing for positive result:
if(myObject != null) {
//do whatever with myObject
}
Sorry, if someone can word it better than me please do.
I personally prefer the first method of checking if the object is null then immediately returning. It allows the "real code" to stay unindented, linear, and can prevent many nested if statements, which I find to be more readable.
Otherwise, both ways are valid and will have the same outcome. Choose whichever works best in your situation (which can depend on any else or else if statements).
Here's a good example:
if (object1 == null) {
return;
}
// do some stuff
if (object2 == null) {
return;
}
// do some stuff
if (object3 == null) {
return;
}
Opposed to:
if (object1 != null) {
// do some stuff
if (object2 != null) {
// do some stuff
if (object3 != null) {
// do some stuff
}
}
}
I find the first one to be much more readable.
Where there is a valid action that can be taken on satisfying a positive condition, such as logging that a result set is empty, or that a variable was not assigned to, then it is better to use positive conditions. APIs can help here, such as Apache Commons StringUtils isNotBlank(), when you are testing strings. However, sometimes the cleanest thing is to go for a negative test, for example only allowing processing to proceed where a variable is non-null.

Best practice for having two if statements from the same bool c++

I have an if statement that [obviously] only runs if the condition is true. After this if statement there is some code that should always run, after that is another if statement that should run under the same condition as the first.
The code in the middle is performing an operation using a particular element of a stack, the ifs on either side perform a push/pop on the stack before and after the operation respectively.
so the logic is something like this:
Do I need to push the stack? yes/no
perform operation on top of stack
Was the stack pushed? (if yes then pop)
items 1 and 3 are the same condition.
This is the code that I first wrote to do this in c++
#include <stdio.h>
#include <stdlib.h>
int somefunction(){
return rand() % 3 + 1; //return a random number from 1 to 3
}
int ret = 0;
//:::::::::::::::::::::::::::::::::::::::
// Option 1 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run = (ret = somefunction()) == 1; //if the return of the function is 1
run = (run || (ret == 2)); //or the return of the function is 2
if (run){ //execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 1 End
//:::::::::::::::::::::::::::::::::::::::
After writing this I thought that it might be more efficient to do this:
//:::::::::::::::::::::::::::::::::::::::
// Option 2 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run;
if (run=(((ret = somefunction()) == 1)||ret == 2)){ //if the return of the function is 1 or 2 then execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 2 End
//:::::::::::::::::::::::::::::::::::::::
I prefer the first method for readability as it is split into several lines whereas the second has two assignments (=) and two comparisons (==) in the same line.
I want to know if it is better to use the second method (for reasons of efficiency or executable size) or if there is a better method than both.
Before anyone says it will only make an almost immeasurable difference, this is in a huge loop that has to run many thousands of times within 1/50 of a second so I would like to save as much time as possible.
Performance should not be your concern: the modern compilers are usually smart enough to optimize the code in any case. The results will be the same if the code is doing essentially the same thing.
So you should prefer the variant which is more readable (and therefore better maintainable).
I would write something like that:
ret = somefunction();
// I don't know what is the semantics of ret == 1, so let's imagine some
bool operationIsPush = (ret == 1);
bool operationIsOnTop = (ret == 2);
if (operationIsPush || operationIsOnTop)
{
//conditional code
}
if (operationIsPush)
{
//more conditional code
}
//unconditional code
if (operationIsPush || operationIsOnTop)
{
// ...
}
I believe there will be no difference in the performance here. The first reason is that your compiler will probably optimize the code in each case. The second is that you just change the place where operations take place (like "I do A->B->C or A->C->B"), not the amount of operations, so it's always the same amount of computing (1 function call, a couple of == and so on).
However consider that this
(run=(((ret = somefunction()) == 1)||ret == 2))
is pretty hard to read.
Correctness is more important than whether you fold two operations assigning a bool into one (which the compiler will probably do anyway).
For pushing/popping a stack, you should use a scopeguard (original article here). This will ensure that if something throws in the "unconditional bit", which you never really know for sure, then it still runs correctly. Otherwise you get funny a surprise (stack off by one, or overflowing).
if theres a situation that you can split "if-else" to distinct huge loops, it will be faster
rather than
loop { if_1 {some work} if_2 {some other work} }
you can
if_1 { loop {work }} if_2 {loop{same work}}
even more extremely, if you can split the most inner "if" sentences, you can have 10-20(dpending on your situation) distinct huge loops that runs x2 x3 faster (if it is slow bacause of "if")

Valgrind detects invalid read error in simple Iterator class

Valgrind detects an invalid read error I don't know how to fix or to be more precise: I don't know what the problem is.
Invalid read of size 8
at 0x443212: std::vector<Tile*, std::allocator<Tile*> >::end() const
by 0x44296C: Collection<Tile*>::Iterator::operator++()
The Iterator class is very simple (and actually a somewhat bad piece of programming) but sufficient for my needs right now. I think there are three methods you should know to hopefully help find my problem:
Iterator(size_t x, size_t y, const TileCollection& tiles)
: mTiles(&tiles)
, mX(mTiles->begin())
, mY(mTiles->at(x).begin())
{
std::advance(mX, x);
std::advance(mY, y);
bool foundFirst = false;
while (!foundFirst)
{
while (mY != mX->end() && *mY == 0) ++mY;
if (mY != mX->end()) foundFirst = true;
else
{
++mX;
if (mX != mTiles->end()) mY = mX->begin();
}
}
}
Iterator Iterator::operator++()
{
bool foundNext = false;
++mY;
while (!foundNext)
{
while (mY != mX->end() && *mY == 0) ++mY;
if (mY != mX->end()) foundNext = true;
else
{
++mX;
if (mX != mTiles->end()) mY = mX->begin();
}
}
return *this;
}
void TileCollection::add(Tile* tile)
{
Point2D p(tile->getPosition());
std::vector<Tile*> tmp(1, (Tile*)0);
if ((size_t)p.x >= mTiles.size())
mTiles.resize(p.x + 1, tmp);
if ((size_t)p.y >= mTiles.at(p.x).size())
mTiles.at(p.x).resize(p.y + 1, (Tile*)0);
mTiles.at(p.x).at(p.y) = tile;
++mNumTiles;
}
The actual code that is causing the valgrind error is the line:
while (mY != mX->end() && *mY == 0) ++mY;
...of the Iterator::operator++ method.
It looks to me that, at the least, the following line in operator++
if (mX != mTiles->end()) mY = mX->begin();
is lacking a suitable else-clause.
Consider what happens when mX actually reaches mTiles->end(): You will enter a new iteration of the outer while loop; the first line in that loop (the line that causes the Valgrind error) will evaluate mX->end() and thus attempt to dereference mX -- but mX is mTiles->end(), and it's not correct to dereference the end iterator of a collection since it doesn't actually reference an element of the collection. It looks to me as if this may be the cause of your Valgrind error.
(Note that the constructor contains essentially the same code.)
More generally, I think you need to think about how you handle reaching the end of your two-dimensional array. How does the client of your Iterator check whether it has reached the end of the iteration? How do you expect your operator++ to handle the case when it reaches the end of the two-dimensional array? Should it protect itself against getting called too often?
You can try to split up the statement in order get find out where the error occurs:
while (mY != mX->end()) // maybe here
{
if (*mY != 0) // maybe here
{
break;
}
++mY; // maybe here
}
Compiling with GCC compiler option -fno-inline helps to get a nicer stack-trace, which can help you to trace the error. It will also make your program very slow, so don't forget to remove it later.