4 ms·
Maybe I'm misunderstanding that part of your post, but when you say char c = 255, you aren't calling it a positive integer. And I'm not sure why you think it sh
by ksaj 7y ago
Maybe I'm misunderstanding that part of your post, but when you say char c = 255, you aren't calling it a positive integer. And I'm not sure why you think it should (it really shouldn't).
Here's what gcc compiles there:
movb $-1, -9(%ebp)
cmpb $10, -9(%ebp)
This isn't a question about %i or %d, since the result is interchangeable in the way you suggest it should be. Try it.
I think the only "trap" is in your ability to recognize 255 isn't always 255, and especially when you call it a char instead of an int. Otherwise it is just 0FFh, which is exactly as expected reading that code. If 'int' is used instead of 'char', you get what you were expecting. Try that, too.
The number of bits is irrelevant, since -1 would be 0FFh or 0FFFFh or 0FFFFFFFFh etc, but only one of those can be represented by 255.
The answer they expect is indeed the correct answer. You fixated on the wrong part and missed the obvious as a result.
- ksaj 7y agoAlso: "Trick is that i,d are the same for printf but match differently for fscanf/scanf according to C11." It's the same for all versions of C. The difference is that f/scanf interprets 0x__h as hexadecimal and 0__ as octal when %i is used. But we aren't using f/scanf here, so it's entirely a moot point since we're using printf where %d and %i are technically equivalent. It would have been a good/obnoxious trick if they made it 0255 instead, though. The LinkdIn question isn't at fault. I'm not even a C programmer (I dabbled, so I can pretty much fake it. You are more experienced than I by quite a bit), yet the answer seems clear enough to me. The use of char instead of int tipped me off to how I would program this in assembler and what the result would be, and gcc seems to agree when I generate assembler from the C code. #include <cstdio> using namespace std; int main() { int a = 255; char b = 255; int c = 0255; char d = 0255; printf("i:\n--\na = %i\nb = %i\nc = %i\nd = %i\n\n", a, b, c, d); printf("d:\n--\na = %d\nb = %d\nc = %d\nd = %d\n\n", a, b, c, d); return(0); } Output: i: -- a = 255 b = -1 c = 173 d = -83 d: -- a = 255 b = -1 c = 173 d = -83