0

The below code takes every 3 consecutive elements in array and check if the middle element is the second smallest among them.


#include <iostream>
using namespace std;
int main() {
  int arr[20];
  int n;
  int x = 0;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }
  for (int i = 0; i < n; i++) {
    if ((i != n - 1) && (i != 0) &&
            (arr[i] > arr[i - 1] && arr[i] < arr[i + 1]) ||
        (arr[i] < arr[i - 1] && arr[i] > arr[i + 1])) {
      x++;
    }
  }
  cout << x;
}

The above code will access arr[-1] and arr[n], because there should be a bracket around the or condition.

When I run this code on Clion 2022 w-64 mingw 9.0 compiler, it prints correct results for every test case I can think of, but when I run it on other compilers, it prints incorrect results.

My questions:

  1. Is this a compiler optimization?
  2. If not, why doesn't it print incorrect results like other compilers.
migo101
  • 11
  • 1

0 Answers0