I have a simple for loop (though it is not the only component within the method) that is compiled with GNU 4.8.1.10 compiler with debugging option is off and optimization levels O-0, O-2 and O-3 distinctively. The loop is as below:
const int iMyConst = 10; // defined in another header
void myFunc(uint8_t ui8InputNum)
{
// some stuff
for(int i=static_cast<int>(ui8InputNum); i<iMyConst; i++)
{ // loop content
}
}
What happens is that, when I call myFunc(10)
(equal to iMyConst
), the for loop is executed. This is not the expected behaviour. Inside the loop I printed the variable values as well. They are printed as expected but with an exception: i<iMyConst
came out to be true
where i
was printed as 10
. Moreover, I forced all process to run on single core, the unexpected behaviour happened again.
I ran the code in debug mode, and saw that the loop is not executed as expected. Then I defined the loop variable as volatile int i
, this time the loop is not executed as well.
The problem might sound odd but it is all what happened. What is the cause of this problem? The system is 64-bit and has 12 cores.
// main.cpp
//============================================================================
// Name : loopProblem.cpp
//============================================================================
#include "a.h"
#include "b.h"
#include <iostream>
int main() {
a* myA = new a;
b* myB = new b;
myB->itsA = myA;
myB->dummyFunc();
delete myA;
delete myB;
return 0;
}
// a.h
#ifndef A_H_
#define A_H_
#include <stdint.h>
// #include <cstdint> not available in c++03
class a
{
public:
a();
~a();
void myFunc(uint8_t ui8InputNum);
};
#endif /* A_H_ */
// a.cpp
#include "a.h"
#include "c.h"
#include <cstdio>
a::a()
{
}
a::~a()
{
}
void a::myFunc(uint8_t ui8InputNum)
{
// some stuff
for(int i=static_cast<int>(ui8InputNum); i<iMyConst; i++)
{
printf("i: %d, comp: %d\n", i, (i<iMyConst));
}
}
// b.h
#ifndef B_H_
#define B_H_
class a;
class b {
public:
b();
~b();
a* itsA;
void dummyFunc();
};
#endif /* B_H_ */
// b.cpp
#include "b.h"
#include "a.h"
#include <cstddef>
b::b() : itsA(NULL)
{
}
b::~b()
{
}
void b::dummyFunc() {
itsA->myFunc(10);
}
// c.h
#ifndef C_H_
#define C_H_
const int iMyConst = 10;
#endif /* C_H_ */