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

后端 未结 10 1759
情话喂你
情话喂你 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:08

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

    // main.c
    #include 
    
    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
    

提交回复
热议问题