Why does C++ standard specify signed integer be cast to unsigned in binary operations with mixed signedness?

前端 未结 3 1910
孤城傲影
孤城傲影 2021-01-17 23:48

The C and C++ standards stipulate that, in binary operations between a signed and an unsigned integer of the same rank, the signed integer is cast to unsigned. There are man

3条回答
  •  日久生厌
    2021-01-18 00:27

    If the signed casting was chosen, then simple a+1 would always result in singed type (unless constant was typed as 1U).

    Assume a was unsigned int, then this seemingly innocent increment a+1 could lead to things like undefined overflow or "index out of bound", in the case of arr[a+1]

    Thus, "unsigned casting" seems like a safer approach because people probably don't even expect casting to be happening in the first place, when simply adding a constant.

提交回复
热议问题