Trying to debug some values in an image (1D array), but found a behavior I cannot understand:
- the code below never hits the
if()
conditions, and nothing is shown to the console.
- by adding back the line
// std::cout << 4 * i << "" << 4 * j << "
";
the code works properly.
- confirmed that the variables
W
, H
and step
, when defined inside the function as local variables, the problem doesnt happen.
- also, when replacing the multiplication
step*i
with the division stx/step
, the problem also doesnt occur.
Running Visual Studio 2019 release x64. The problem seems to do with some compiler optimization, but I can't figure out what I am doing wrong!
void testcode(int W, int H, int step) {
int n = 30;
int h = H/step;
int w = W/step;
float* arr = new float[h * w];
memset(arr, 0, h * w *sizeof(float));
int stx = 500, ndx = 550;
int y = 900;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int cost_idx_sc = i * w + j;
int cost_idx = step * i * w + j * step;
// std::cout << 4 * i << "" << 4 * j << "
";
#if 0
if ((i >= stx/step) && (i <= ndx/step)) {
if (j == y/step) {
std::cout << (float)(arr[cost_idx_sc]) << "";
system("pause");
}
}
#else
if (((step*i) >= stx ) && ((step*i) <= ndx )) {
if ((step*j) == y ) {
std::cout << (float)(arr[cost_idx_sc]) << "";
system("pause");
}
}
#endif
}
}
system("pause");
delete[] arr;
}
int main(){
testcode(2000,1500,4);
return 0;
}
question from:
https://stackoverflow.com/questions/65840115/code-behaving-differently-with-and-without-a-stdcout-statement 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…