electro177's blog

By electro177, history, 5 weeks ago, In English

while this is working fine ~~~~~ Your code here... bool emp (int i, int j) { if ( i >= 0 && i < n && j >= 0 && j < m && s[i][j] == '.' )return 1; else return 0;

} ~~~~~

this is giving run time error ~~~~~ Your code here...

bool emp (int i, int j) { if ( s[i][j] == '.' && i >= 0 && i < n && j >= 0 && j < m )return 1; else return 0;

} ~~~~~

does anyone know the reason

 
 
 
 
  • Vote: I like it
  • -20
  • Vote: I do not like it

»
5 weeks ago, # |
Rev. 2   Vote: I like it +17 Vote: I do not like it

It happens because operator&& is calculated lazily. It means that if you have expression of kind: A && B && C && D && ... and, for example, A == false, then B, C and others will not be calculated.

In the first case you firstly check that i and j are in a good range and then check array element. It's OK because if indexes are incorrect, you won't check s[i][j] == '.'. In the second case you do it in another order and can go out of range.

»
5 weeks ago, # |
  Vote: I like it +8 Vote: I do not like it

emp(-1, -1)