Home > Net >  For loop won't run when comparing length of Vector to a negative number in C
For loop won't run when comparing length of Vector to a negative number in C

Time:10-18

I have a pair of nested for loops and I am attempting to print the following structure:

  0 1 2 3 4 
0 - - - - - 
1 - - - - - 
2 - - - - - 
3 - - - - - 
4 - - - - - 

If I attempt to initialize the row counter of the outer loop to -1, and compare it to the length of the vector using .length(), the outer loop simply does not run. I've tested this by putting print statements within the outer loop and they never get executed. My compiler also issues the following warning: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<std::vector<char> >::size_type’ {aka ‘long unsigned int’} [-Wsign-compare] I attempted to change the row counter from an int to a long unsigned int, and while that suppresses the warning message, the loop still won't run. What is the reason for this behavior and how can I resolve it?

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

void print_board(vector<vector<char>> board)
{
    int row, col;

    cout << "  ";
    for (row = -1; row < board.size(); row  )
    {
        if (row > -1)
            cout << row << " ";

        for (col = 0; col < board[row].size(); col  )
        {
            if (row == -1)
                cout << col << " "; 
            else
                cout << board[row][col] << " ";
        }

        cout << endl;
    }
}

int main()
{
    int max_rows = 5;
    vector<vector<char>> player_one_board(max_rows, vector<char>(max_rows, '-'));

    print_board(player_one_board);

    return 0;
}

CodePudding user response:

If all you're doing is printing out the board, you really shouldn't be starting at -1, but 0 instead. That is:

std::cout << "  ";
for (std::size_t row = 0; row < board[0].size();   row) {
   std::cout << row << " ";
}

std::cout << std::endl;

for (std::size_t row = 0; row < board.size();   row) {
    std::cout << row << " ";
    for (std::size_t col = 0; col < board[row].size();    col) {
        std::cout << board[row][col] << " ";
    }

    std::cout << endl;
}

CodePudding user response:

Vector can not consist from less than 0 elements. Initialize row with 0, or skip loop for col using continue if row is less than 0.

CodePudding user response:

The warning basically tells you everything: board.size() is unsigned, so should be row. When you supress the warning, the problem now isn't the comparison, but how row is initialized with -1. It really shouldn't be, because it's unsigned, it can't hold -1. Instead, it silently gets initialized with some positive number. At this point, it's really C 's fault that you don't get another warning or error. Its type system is kind of weak because of C legacy.

The solution here is to keep row unsigned and express your logic differently, without -1.

  •  Tags:  
  • c
  • Related