Why are unsigned integers error prone?

后端 未结 8 1099
眼角桃花
眼角桃花 2020-12-13 08:28

I was looking at this video. Bjarne Stroustrup says that unsigned ints are error prone and lead to bugs. So, you should only use them when you really need t

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 08:43

    The big problem with unsigned int is that if you subtract 1 from an unsigned int 0, the result isn't a negative number, the result isn't less than the number you started with, but the result is the largest possible unsigned int value.

    unsigned int x = 0;
    unsigned int y = x - 1;
    
    if (y > x) printf ("What a surprise! \n");
    

    And this is what makes unsigned int error prone. Of course unsigned int works exactly as it is designed to work. It's absolutely safe if you know what you are doing and make no mistakes. But most people make mistakes.

    If you are using a good compiler, you turn on all the warnings that the compiler produces, and it will tell you when you do dangerous things that are likely to be mistakes.

提交回复
热议问题