Why is int rather than unsigned int used for C and C++ for loops?

后端 未结 10 2096
日久生厌
日久生厌 2020-12-02 15:50

This is a rather silly question but why is int commonly used instead of unsigned int when defining a for loop for an array in C or C++?

<         


        
10条回答
  •  旧时难觅i
    2020-12-02 16:06

    Consider the following simple example:

    int max = some_user_input; // or some_calculation_result
    for(unsigned int i = 0; i < max; ++i)
        do_something;
    

    If max happens to be a negative value, say -1, the -1 will be regarded as UINT_MAX (when two integers with the sam rank but different sign-ness are compared, the signed one will be treated as an unsigned one). On the other hand, the following code would not have this issue:

    int max = some_user_input;
    for(int i = 0; i < max; ++i)
        do_something;
    

    Give a negative max input, the loop will be safely skipped.

提交回复
热议问题