d22shen
d22shen

Reputation: 31

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!

Upvotes: 1

Views: 7290

Answers (1)

chux
chux

Reputation: 154392

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.

Upvotes: 2

Related Questions