1

I have an 2d vector as below.

vector<vector<int>> mat = {
        {1,1,0,1},
        {1,0,0,0},
        {0,0,0,1},
        {0,0,1,1},
        {0,1,0,0}
    };

What I want to do is check if the element is left edge or it's left element is 1.

So what I tried to do is:

for (int r = 0; r < 5; ++r){
   for (int c = 0; c <4; ++c){
       if (r - 1 < 0 || mat[r-1][c] == 1)
   }
}

My question is how is this line executed?

if (r - 1 < 0 || mat[r-1][c] == 1)

Does it caculate the r-1 and mat[r-1][c] == 1 seperately and then do or operation? In this case, there may be illegal memory access when r == 0?

Seems my code runs ok but I don't this makes sense to me.

Could someone help me with this?

BigTree
  • 23
  • 1
  • 4
  • 1
    Good question, this is called short-circuiting. The other question contains the details. TL;DR: It's fine, and you don't have to worry about `mat[r-1]`. – Zeta Nov 24 '21 at 07:23
  • 1
    Further, if `(r-1 < 0)` evaluates to true, then `mat[r-1][c]` is not evaluated. – selbie Nov 24 '21 at 07:25

0 Answers0