I have a line in my program that goes like: sprintf (line, "%s [%lu..%lu]", pp->help, min, max);
where min, max;
are unsigned long
and line
is char[SOME_SIZE]
. Before the sprintf
is invoked I call a function that can assign negatives to min
and min gets the value of -5
which translates to 4294967291
because it's unsigned.
So I tried to do something like:
if((long)min < 0) // works fine because 4294967291 has the binary of 0x1...
sprintf (line, "%s [%d..%d]", pp->help, (long)min, max);
but that does not work. The if is true, but I still get positive numbers (i.e. 4294967291
) when I print line, how can I fix this?
NOTE: I'm not sure how the print is implemented in the end of the execution but right now the sprintf
itself is not working as i want it to, as it adds unsigned to the string instead of signed.
this is a simplification of my code:
unsigned long min = foo() /* in this case -5 */, max = goo() /* in this case 5*/;
char line[100];
if((long)min < 0){
sprintf (line, "%s [%d..%d]", pp->help, (long)min, max);
}// when it prints I get [4294967291..5] instead of [-5..5]
else{
sprintf (line, "%s [%lu..%lu]", pp->help, min, max);
}
EDIT: I tried to get similar results on my gcc but failed. But I saw something very strange that could explain this. When line
is declared, it is char[]
, but when the debugger reaches the sprintf
, line
is identified as unsigned char
... but sadly I can't post the code here.