I am using Intel C++ compiler 12.0, and working on a program similar to the following, which is very simple and straightforward. The while loop should stop in the first run. However, when I build the code using /O2 flag with the Intel compiler, the while loop never stops. If I disable the optimization, or use visual C++, the loop exits normally. If I change pt->flag to p.flag, which I suppose is the same thing, the loop exits normally too. I think it has something to do with Intel's optimization. Is this a bug in the Intel compiler? or I missed something here?
#include <iostream>
using namespace std;
struct para {
int i;
int flag;
};
int main(int argc, char **argv)
{
para p;
p.i = 0;
p.flag = 1;
para * pt = &p;
cout << "loop started" << endl;
int i;
while (p.flag) {
if (p.i == 0) {
for (i=0; i<1; i++) {
if (p.flag != 1)
break;
}
if (i==1) {
pt->flag = 0;
}
}
}
cout << "loop stopped" << endl;
return 1;
}
Updates: Thanks for everybody's answer. I am confused by the explanation of "pointer aliasing". If p is in the registers and pt can't access it, why the following code will break the while loop with the intel compiler? Firstly "pt->flag = 0;" should never take effect because i=0. Secondly even if it's in effect, shouldn't "pointer aliasing" prevent p being modified?
BTW: Can anybody let me know how to turn on/off the pointer aliasing in Visual Studio with intel compiler? Thanks!
#include <iostream>
using namespace std;
struct para {
int i;
int flag;
};
int main(int argc, char **argv)
{
para p;
p.i = 0;
p.flag = 1;
para * pt = &p;
cout << "loop started" << endl;
int i=0;
while (p.flag) {
if (p.i == 0) {
//for (i=0; i<