0

arr[n] == 1 -> this code contains error

but the code below works well

Im curious that computer compute(n < arr.size()) and think arr[n] == 1 code doesn't have to compute because (n < arr.size() && arr[n] == 1) is false whether arr[n] == 1 is true or false.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n, x;
vector<int> arr;

int main() {
    
    
    arr.push_back(1);
    arr.push_back(1);
    arr.push_back(1);

    int n = 3;
    if (n < arr.size() && arr[n] == 1) {
        cout << 1;
    }

}

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n, x;
vector<int> arr;

int main() {
    
    
    arr.push_back(1);
    arr.push_back(1);
    arr.push_back(1);

    int n = 3;
    if (n < arr.size()) {
        if (arr[n] == 1) {
            cout << 1;
        }
    }

}

i want to know the difference between upper code and lower code thankx

  • 4
    `arr[n] == 1` is not executed because `n < arr.size()` condition is false. There is no functional difference between the two examples shown. `&&` operator short-circuits: that is, when evaluating the expression `A && B`, `A` is tested first; if it's false, `B` is not computed at all. Similarly, with `A || B`, if `A` is true then `B` is not evaluated. – Igor Tandetnik Jul 01 '23 at 04:39
  • Another reason is that the computer could only execute one instruction at the same time. Besides, in programming, your example is commonly used, and if we change `arr[n] == 1` to an expensive operation, not computing it can save a lot of time. – cup11 Jul 01 '23 at 05:07
  • Side note there is no reason to have variables outside your main (global variables). Try to avoid them as much as you can. Alse very important : the fact that a C++ program compiles and seems to run doesn't mean it is correct. – Pepijn Kramer Jul 01 '23 at 05:36
  • Try your code again, but replace `arr[n]` with `arr.at(n)` and see what happens. – Pepijn Kramer Jul 01 '23 at 05:38
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/4641116) – Eljay Jul 01 '23 at 13:50

0 Answers0