The importance of declaring a variable as unsigned

前端 未结 14 3263
臣服心动
臣服心动 2021-02-20 05:55

Is it important to declare a variable as unsigned if you know it should never be negative? Does it help prevent anything other than negative numbers being fed into a function th

14条回答
  •  我在风中等你
    2021-02-20 06:39

    One minor nicety is that it cuts down on the amount of array bounds checking testing that might be necessary... e.g. instead of having to write:

    int idx = [...];
    if ((idx >= 0)&&(idx < arrayLength)) printf("array value is %i\n", array[idx]);
    

    you can just write:

    unsigned int idx = [...];
    if (idx < arrayLength) printf("array value is %i\n", array[idx]);
    

提交回复
热议问题