简体   繁体   中英

How to assign an int to unsigned long using C?

I am using C language. There is a function named "npu_session_total". Then, I will use the return value of this func and assign it to an unsigned long variable "accelerated_count".

int npu_session_total(void)
{
    // this will return an int
    return atomic_read(&npu_session_count);
}
........
unsigned long accelerated_count = npu_session_total();

Will this cause any problems? How can I do the cast?

Thanks!

Assigning an int to a unsigned long can be done simply as OP did. It is well defined in C. When some_int_value >= 0 it will always fit unchanged into an unsigned long .

INT_MAX <= UINT_MAX <= ULONG_MAX

No cast, masking, nor math is needed - just like OP did.

unsigned long some_unsigned_long_object = some_int_value;

The trick is when some_int_value < 0 . The value saved will be some_int_value + ULONG_MAX + 1 . @AnT Now is this OK for OP's code? Perhaps not.

A safer conversion would test for negativeness first.

int session_total = npu_session_total();
if (session_total < 0) {
  Handle_Negative_Case(session_total);
}
else {
  unsigned long accelerated_count = npu_session_total();
  ...
}

@OP comments that the int value should never be negative. Defensive coding would still detect negative values and handle that. Maybe a simple error message and exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM