Search code examples
c++arraysc++11unsigned

why declare "score[11] = {};" and "grade" as "unsigned" instead of "int'


I'm new to C++ and is trying to learn the concept of array. I saw this code snippet online. For the sample code below, does it make any difference to declare:

unsigned scores[11] = {};
unsigned grade; 

as:

int scores[11] = {};
int grade; 

I guess there must be a reason why score[11] = {}; and grade is declared as unsigned, but what is the reason behind it?

int main() {
    unsigned scores[11] = {};
    unsigned grade;
    while (cin >> grade) {
        if (0 <= grade <= 100) {
            ++scores[grade / 10];
        }
    }
    for (int i = 0; i < 11; i++) {
        cout << scores[i] << endl;
    }
}

Solution

  • Unsigned variables

    Declaring a variable as unsigned int instead of int has 2 consequences:

    • It can't be negative. It provides you a guarantee that it never will be and therefore you don't need to check for it and handle special cases when writing code that only works with positive integers
    • As you have a limited size, it allows you to represent bigger numbers. On 32 bits, the biggest unsigned int is 4294967295 (2^32-1) whereas the biggest int is 2147483647 (2^31-1)

    One consequence of using unsigned int is that arithmetic will be done in the set of unsigned int. So 9 - 10 = 4294967295 instead of -1 as no negative number can be encoded on unsigned int type. You will also have issues if you compare them to negative int.

    More info on how negative integer are encoded.

    Array initialization

    For the array definition, if you just write:

    unsigned int scores[11];
    

    Then you have 11 uninitialized unsigned int that have potentially values different than 0.

    If you write:

    unsigned int scores[11] = {};
    

    Then all int are initialized with their default value that is 0.

    Note that if you write:

    unsigned int scores[11] = { 1, 2 };
    

    You will have the first int intialized to 1, the second to 2 and all the others to 0.

    You can easily play a little bit with all these syntax to gain a better understanding of it.

    Comparison

    About the code:

    if(0 <= grade <= 100)
    

    as stated in the comments, this does not do what you expect. In fact, this will always evaluate to true and therefore execute the code in the if. Which means if you enter a grade of, say, 20000, you should have a core dump. The reason is that this:

    0 <= grade <= 100
    

    is equivalent to:

    (0 <= grade) <= 100
    

    And the first part is either true (implicitly converted to 1) or false (implicitly converted to 0). As both values are lower than 100, the second comparison is always true.