Advice on unsigned int (Gangnam Style edition)

后端 未结 5 596
轻奢々
轻奢々 2021-02-02 11:38

The video \"Gangnam Style\" (I\'m sure you\'ve heard it) just exceeded 2 billion views on youtube. In fact, Google says that they never expected a video to be greater than a 32-

5条回答
  •  面向向阳花
    2021-02-02 12:10

    Google states that: "Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation."

    I personally use unsigned ints as index parameters.

    int foo(unsigned int index, int* myArray){
        return myArray[index];
    }
    

    Google suggests: "Document that a variable is non-negative using assertions. Don't use an unsigned type."

    int foo(int index, int* myArray){
        assert(index >= 0);
        return myArray[index];
    }
    

    Pro for Google: If a negative number is passed in debug mode my code will hopefully return an out of bounds error. Google's code is guaranteed to assert.

    Pro for me: My code can support a greater size of myArray.

    I think the actual deciding factor comes down to, how clean is your code? If you clean up all warnings, it will be clear when the compiler warns you know when you're trying to assign a signed variable to an unsigned variable. If your code already has a bunch of warnings, the compiler's warning is going to be lost on you.

    A final note here: Google says: "Sometimes gcc will notice this bug and warn you, but often it will not." I haven't seen that to be the case on Visual Studio, checks against negative numbers and assignments from signed to unsigned are always warned. But if you use gcc you might have a care.

提交回复
热议问题