Why Is Comparing if an Unsigned Int >= 0 a “Pointless Comparison”?

后端 未结 10 1740
情话喂你
情话喂你 2021-02-12 10:44

I got warning:

Pe186 \"Pointless comparison of unsigned int with zero\"

when I tried to compile the following code:



        
相关标签:
10条回答
  • 2021-02-12 11:04

    The warning complains about your for loop break condition clLoop >= 0. The loop will end if clLoop gets negative, but that will never happen for an unsigned int.

    0 讨论(0)
  • 2021-02-12 11:07

    You should remove = in

    clLoop >= 0
    

    Let's say your cpLoopStart is 5.

    Then, clLoop value in the further iteratiosn would be -

    clLoop = 4;
    clLoop = 3;
    clLoop = 2;
    clLoop = 1;
    clLoop = 0;
    clLoop = 0;
    clLoop = 0;
    clLoop = 0;
    |
    |
    |
    Infinite times.
    
    0 讨论(0)
  • 2021-02-12 11:08

    do{} while() can help you to use unsigned types of variable for loop without integer overflow:

    // main.c
    #include <stdio.h>
    
    int main(void)
    {
    
        int array[] = {1,2,3,4,5,6,7,8,9,10};
        unsigned int size = sizeof(array)/sizeof(int); // size == 10;
    
        unsigned int i = size;
        do
        {
            i--;
            printf("Index: %u, content: %d\n",i,array[i]);
    
        } while(i > 0);
    
        return 0;
    }
    

    And compile it with:

    gcc -std=c11 -Wall -Wextra -Wpedantic main.c
    

    Output:

    Index: 9, content: 10
    Index: 8, content: 9
    Index: 7, content: 8
    Index: 6, content: 7
    Index: 5, content: 6
    Index: 4, content: 5
    Index: 3, content: 4
    Index: 2, content: 3
    Index: 1, content: 2
    Index: 0, content: 1
    
    0 讨论(0)
  • 2021-02-12 11:14

    I think you meant to say

    for(clLoop = cpLoopStart; clLoop; clLoop--)                                  
    { //Do something
    }
    
    0 讨论(0)
提交回复
热议问题