Unsigned int to int and vice-versa

Nov 21, 2014 at 11:41pm
If I know that the number I'm dealing with is greater/equal to 0, is it perfectly fine to do
 
static_cast<unsigned>(my_int)
and
static_cast<int>(my_unsigned_int) ?
Also my_unsigned_int won't be big enough for overflow issues.

I tried to search this but couldn't get an exact answer from standard quotes.
Last edited on Nov 21, 2014 at 11:43pm
Nov 22, 2014 at 3:06am
Regular type casting should be fine for that.

1
2
int x;
unsigned int y = (unsigned int)x;


Of course if it's a negative number you will end up with some strange results.
Last edited on Nov 22, 2014 at 3:06am
Nov 22, 2014 at 3:08am
You should be able to implicitly cast from unsigned to signed and vice versa.

P.S. when I say implicitly I mean like
1
2
3
int i = 0;
unsigned j = i; //i is implicitly casted from signed to unsigned
i = j; //j is implicitly casted from unsigned to signed 
Though you can also safely explicitly cast using the static_cast like you are.
Last edited on Nov 22, 2014 at 3:11am
Nov 22, 2014 at 5:47am
Thanks, that clears things up.
@giblit It was more about using the > operator between an int and unsigned int that was giving (permissible) warnings, I'm using the cast to just avoid that minor complaint from it.

In case it might be of interest, the reason I am mixing signed and unsigned is because the interface I'm adhering to needs unsigned as the width/heights, but I have some could-be-negative "offsets" in my images to account for some position stuff.

But yeah it's clear now.
Last edited on Nov 22, 2014 at 5:50am
Topic archived. No new replies allowed.