Thread: check if index is out of bounds to satisfy if conditions

  1. #1
    Registered User
    Join Date
    Dec 2019
    Posts
    5

    check if index is out of bounds to satisfy if conditions

    Hello I am practicing working with 2d arrays in c++ and my question is for example if I want to check if 4 has either 0 or 11 to the north , east, south, west as neighbour it should return false.
    this is my function to test
    Code:
     bool testG(int grid[ROW][COL], int row, int col) {
         if (row < 0 || col < 0 || row >= ROW || col >= COL)
             return false;
         return grid[row][col] == 0 || grid[row][col] == 11;
    }
    
    //then this is where I check if north, west, south , east are not  0 or 11
    if(testG(grid,-1,0) && testG(grid,0,-1) && testG(grid,1,0) && testG(grid,0,1)) 
    { 
      return false;
    }
    if I remove (testG(grid,-1,0) && testG(grid,0,-1) then it works and that is because west and north of the node 4 is out of bounds.

    Now my problem is since west of 4 and north of four is out of bounds it will never return false.
    How could I optimise my if condition to make it return false?
    This is my 2d array

    This should return false
    Code:
        int grid[ROW][COL] = {{ 4, 11, 1, 1 },
                      { 0, 0, 1, 0 },
                      { 0, 1, 5, 0},
                      { 0, 5, 0,0 } };
    This should return true
    Code:
        int grid[ROW][COL] = {{ 4, 11, 1, 1 },
                      { 1, 1, 1, 0 },
                      { 0, 1, 5, 0},
                      { 0, 5, 0,0 } };
    I hope my question was clear , thank you in advance.






  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,629
    So make your condition
    Code:
         if (row < 0 || col < 0 || row >= ROW || col >= COL)
             return true;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I keep getting this error index out of bounds
    By artistunknown in forum C# Programming
    Replies: 11
    Last Post: 06-30-2015, 12:04 AM
  2. index out of bounds error
    By artistunknown in forum C# Programming
    Replies: 5
    Last Post: 06-27-2014, 11:25 PM
  3. Vector bounds check
    By micha_mondeli in forum C++ Programming
    Replies: 3
    Last Post: 04-07-2005, 06:39 AM
  4. overload contructors || check bounds of array
    By xion in forum C++ Programming
    Replies: 2
    Last Post: 05-24-2004, 07:43 AM
  5. illegal vector index and checking bounds
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 12-23-2001, 11:36 AM

Tags for this Thread