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 that shouldn’t have them?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Declaring variables for semantically non-negative values as
unsignedis a good style and good programming practice.However, keep in mind that it doesn’t prevent you from making errors. If is perfectly legal to assign negative values to unsigned integers, with the value getting implicitly converted to unsigned form in accordance with the rules of unsigned arithmetic. Some compilers might issue warnings in such cases, others will do it quietly.
It is also worth noting that working with unsigned integers requires knowing some dedicated unsigned techniques. For example, a “classic” example that is often mentioned with relation to this issue is backward iteration
The above cycle looks natural with signed
i, but it cannot be directly converted to unsigned form, meaning thatdoesn’t really do what it is intended to do (it is actually an endless cycle). The proper technique in this case is either
or
This is often used as an argument against unsigned types, i.e. allegedly the above unsigned versions of the cycle look “unnatural” and “unreadable”. In reality though the issue we are dealing here is the generic issue of working near the left end of a closed-open range. This issue manifests itself in many different ways in C and C++ (like backward iteration over an array using the “sliding pointer” technique of backward iteration over a standard container using an iterator). I.e. regardless of how inelegant the above unsigned cycles might look to you, there’s no way to avoid them entirely, even if you never use unsigned integer types. So, it is better to learn these techniques and include them into your set of established idioms.