c++debuggingcodeblocks

Why I get different value for my variable? (C++)


Why I get different value for "k" variable when I add something to the end of my code. The k's value is 4 but if I add that little part in the comment it changes to 5. I guess that shouldnt affect anything. Am I wrong? Or what can I do to solve this annyoying problem?

My code (Code:blocks)

#include <iostream>

using namespace std;

int main()
{
int N = 10;
int A[]={1100, 700, 950, 780, 850, 1050, 750, 950, 950, 700};

int k = 0;
 if (A[0] > 800) { 
    k = 1;
} else {
    k = 0;
}
for (int i = 1; i < N; i++) {
    if (A[i]<= 800 && A[i+1] > 800) {
        k++;
    }
}
cout << k << endl;

/* int max_size = k;
int h[max_size]; */
}

Solution

  • Undefined behaviour

    In computer programming, undefined behavior (UB) is the result of executing computer code written in a programming language for which the language specification does not prescribe how that code should be handled. Undefined behavior is unpredictable and a frequent cause of software bugs.

    Consider this piece of code:

    for (int i = 1; i < N; i++) {
        if (A[i]<= 800 && A[i+1] > 800) {
            k++;
        }
    }
    

    When i is equal to N - 1, the condition inside the loop becomes:

    if (A[N-1]<= 800 && A[N] > 800)
    

    the result of which results to undefined behaviour.

    You could solve this by changing the limit in the for which is probably what you wanted in the first case:

    for (int i = 1; i < N - 1; i++)
    

    or by changing the condition inside the loop to this:

    if (A[i - 1]<= 800 && A[i] > 800)