C/C++ use of int or unsigned int

后端 未结 6 1308
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 09:17

In a lot of code examples, source code, libraries etc. I see the use of int when as far as I can see, an unsigned int would make much more sense.

One pl

6条回答
  •  天涯浪人
    2021-01-01 10:15

    Using unsigned can introduce programming errors that are hard to spot, and it's usually better to use signed int just to avoid them. One example would be when you decide to iterate backwards rather than forwards and write this:

    for (unsigned i = 5; i >= 0; i--) {
        printf("%d\n", i);
    }
    

    Another would be if you do some math inside the loop:

    for (unsigned i = 0; i < 10; i++) {
        for (unsigned j = 0; j < 10; j++) {
            if (i - j >= 4) printf("%d %d\n", i, j);
        }
    }
    

    Using unsigned introduces the potential for these sorts of bugs, and there's not really any upside.

提交回复
热议问题