Unsigned and Signed ints in C++

Started by
1 comment, last by Dave Hunt 19 years, 3 months ago
Okay, I assign a variable unsigned and it keeps comming up as a positive Well heres the code: // Assuming m_Font is already declared in DirectX short int m = -2; sprintf(varM, "Variable M: %lu ", m); m_Font.Print(varM,2,2,400,100); OUTPUT: Variable M: 65534 It should be a negative number... can anyone tell me how to make it negative?
---------------------------------The Shadow Sun - Want Your Writing Exposed?
Advertisement
Unsigned integers cannot represent negative numbers. You need to use a default (signed) integer.
"What are you trying to tell me? That I can write an O(N^2) recursive solution for a 2-dimensional knapsack?" "No, programmer. I'm trying to tell you that when you're ready, you won't have to." -Adapted from "The Matrix"
Quote:Original post by zealotgi
Okay, I assign a variable unsigned and it keeps comming up as a positive


That's what "unsigned" means, no sign.

Quote:
Well heres the code:

// Assuming m_Font is already declared in DirectX

short int m = -2;
sprintf(varM, "Variable M: %lu ", m);
m_Font.Print(varM,2,2,400,100);


OUTPUT:

Variable M: 65534


It should be a negative number... can anyone tell me how to make it negative?


Two problems here, both with the "%lu". First, the 'u' means unsigned. Use 'd' instead. Second, the 'l' means long, but you gave it a short (which is promoted to an int on the stack, so the 'd' is still ok). Since sprintf is expecting a long and all you have is an int, it could cause problems depending on the size of an int on your system.

At any rate, change the "Variable M: %lu " to "Variable M: %d " and you should get what you expected.

This topic is closed to new replies.

Advertisement