Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

c++ - Code behaving differently with and without a std::cout statement

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...