I am asking this question for two different languages: C and C++.
What is best practice when calling functions that have an opposite integer sign expectation to what we require in our code?
For example:
uint32 _depth; // uint32 = DWORD int depth; _BitScanForward(&_depth, (uint32)input); // DWORD, DWORD depth = (int)_depth;
_BitScanForward is expecting DWORD (uint32) parameters. The variable input
is of int16 type and I need to process the result _depth
as an int32 in my code.
input
as shown? I know the complier will probably do it for me, but what is best practice?_depth
as int32 and therefore avoid having to cast it afterwards as shown?NOTE:
My comment about the complier is based on experience. I wrote code that compiled with no warnings in VS but crashed on execution. Turned out I was calling a function with an incorect width int. So I don't leave this topic up to the compiler any more.
EDIT:
The answers are helpful, thanks. Let me refine my question. If there are no width issues, i.e. the function is not expecting a narrower int than what is being passed in (obvioulsy will fail), then is it okay to rely on the compiler to handle sign and width differences?
Unsigned is good programming practice to indicate the intention, to yourself and others, of use of the data element - just in the same way all types are used. For example, a normal array index variable should never be negative and so declaring the variable unsigned should be best practice.
The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.
then your compiler may issue a warning like "comparison between signed and unsigned integer expressions". Briefly, the problem is that a standard C++ compiler will handle this code by casting x as an unsigned int before doing the comparison, which may turn a negative number into a large positive number.
Unsigned can hold a larger positive value and no negative value. Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative. Signed integers can hold both positive and negative numbers.
I would strongly recommend to hide that function into a custom wrapper function which agrees with your preferred API (and within this function do proper explicit casting). In the case of using compiler-specific functions this has the additional advantage that it will be much easier to port it to different compilers (should you ever want to do that), by just re-implementing that wrapper function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With