Pelles C forum

C language => Beginner questions => Topic started by: sgraffe on March 10, 2018, 05:27:40 PM

Title: Curious behavior of compiled program (if jumping out of while loop)
Post by: sgraffe on March 10, 2018, 05:27:40 PM
Hello, all:

I am getting strange results when debugging this code:
(The logic of the code is wrong because I am just modifying it)

Code: [Select]
while(projTable->readNextRecord(projTable) != EOF)
{
int thisProjectID = atoi(projTable->readField(projTable, proj_id));
if (projectID_ == 0)
{
projectID_ == thisProjectID;
break;
}
if (thisProjectID == projectID_)
break;
}
if (projectID_ == 0)
return setErrStatus(projectNotFound);
At the beginning, projectID_ is zero. When the program reaches the first if (if (projectID_ == 0))
   it jumps out of the loop to the line with the return.


A new version of the code:
Code: [Select]
bool found = false;
int thisProjectID = 0;
while(!found && projTable->readNextRecord(projTable) != EOF)
{
thisProjectID = atoi(projTable->readField(projTable, proj_id));
if (projectID_ == 0)
{
projectID_ == thisProjectID;
found = true;
break;
}
if (thisProjectID == projectID_)
{
found = true;
break;
}
}
if (! found)
if (projectID_ == 0)

In this case, from the first if, it jumps inside the second if (if (thisProjectID == projectID_)), to the break statement.

My final working version is this (it works ok):
Code: [Select]
bool found = false;
int thisProjectID = 0;
while(!found && projTable->readNextRecord(projTable) != EOF)
{
thisProjectID = atoi(projTable->readField(projTable, proj_id));
if (projectID_ == 0)
found = true;
else
found = thisProjectID == projectID_;
}
if (!found)
return setErrStatus(projectNotFound);

Can anybody find an explanation of this behavior?
This is so simple that I am sure I screwed it somewhere.
It looks like the program  does not execute what the source code says.

Thank you for your time,
Simon
Title: Re: Curious behavior of compiled program (if jumping out of while loop)
Post by: frankie on March 10, 2018, 10:40:17 PM
This is due to optimizations. The line:
Code: [Select]
projectID_ == thisProjectID;Isn't an assignment, the operator == compares the 2 values, but have no side effects, so the compiler optimizes it out omitting to emit any code for it.
Said that, it happens the following:
Title: Re: Curious behavior of compiled program (if jumping out of while loop)
Post by: sgraffe on March 10, 2018, 11:22:47 PM
I knew I had screwed it!
But four eyes were needed to find it.
That statement should read
    projectID_ = thisProjectID;

and not
projectID_ == thisProjectID;

Thank you!

Simon