#Clarification on comparing int with size_t in conditions

7 messages · Page 1 of 1 (latest)

empty gazelle
#

Hi, I'm attempting the 8 queens problem (place 8 queens on a chess board with any of them attacking each other) in C99.
One of the things I was trying to do was to compare vars of int and size_t as shown here:

    /* Attack all cells diagonal of pos (neg slope) */
    for (int i = -8; i < boardObj->size; i++) {
        printf("Coords: [%d, %d]\n", currentPos.x + i, currentPos.y + i);
        if ((currentPos.x + i >= 0) && 
            (currentPos.y + i >= 0)) {
            boardObj->board[currentPos.x + i][currentPos.y + i] = ATTACKED;
        }
    }

    /* Attack all cells diagonal of pos (pos slope) */
    for (int j = -8; j < boardObj->size; j++) {
        printf("Coords: [%d, %d]\n", currentPos.x - j, currentPos.y + j);
        if ((currentPos.x - j >= 0) && 
            (currentPos.y + j >= 0)) {
            boardObj->board[currentPos.x - j][currentPos.y + j] = ATTACKED;
        };
    }

So my questions are:

  1. Why does the program skip the loops without casting the boardObj->size of type size_t?
  2. Why does gcc only throw this up as a warning and not an error, allowing it to compile?
  3. Why does it work if int is positive? Is it in terms of how the values are represented in binary? (1's or 2's complement or signed notation)
dusty tulipBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

hallow linden
#

because size_t has a wider type than int, the int is being cast to a wider type.
and because your int is negative when casted it will contain a very large value most likely greater than board size

#

and you should get a warning for this, although when using msvc there happens to be a bug that does not warn users about unsigned comparison

#

you should cast your types for your comparison and it may be helpful to write a 'safe' casting function something along these lines:

i32 TruncateOrFail_i32(u64 Value)
{
    if (Value > I32_MAX)
    {
        Assert(0);
    }
    return (i32)Value;
}```
empty gazelle
#

ah okay. Never thought of doing it with that in mind. Thanks for the reply!

#

!solved