As you can see, the
if statement on the line 35 is false. Why is the body of the
if statement being executed?
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
The statement is actually true. The issue here is how the values are being displayed, and the clue is to look at the pattern of your
if ((buffer == 255 && buffer == 216 && buffer == 255 && buffer == 224) || (buffer == 255 && buffer == 216 && buffer == 255 && buffer == 255))
If we look only at where the numbers are similar and where they are different, the pattern you are checking for in the first four characters of the buffer is
A B A C or
A B A A. Now, what is the pattern in the characters you see in
$2 = "\377\330\377\340\000\020\JFIF\000...
The first four characters are
\377\330\377\340, which matches the pattern
A B A C. That's your first clue - you can figure it out yourself, but here are some hints before I give you the solution.
What are the different
printfspecifiers for displaying numeric values?
Can you figure out a way to write 255, 216 and 224 as
"\340"? Try subtracting to see how far apart the values are.
Google "c 255 377"
If you went through the hints you have surely figured it out by now, but if you were too impatient, here's the answer:
The values are being printed out in octal representation, also known as base-8. Unlike hexadecimal, which includes the letters
a-f, octal can look a lot like regular old decimal (base-10) notation. But when you see the
\escape character, you should think aha! That's not just a number or a character, it's some kind of code. Then you just have to figure out what the code is.
By the way, you could write that same
if statement a little more compactly and efficiently, since it's testing the same exact thing for the first three characters. Like this:
if (buffer == 255 && buffer == 216 && buffer == 255 && (buffer == 224 || buffer == 255))
This way, as soon as any of the first, second or third characters don't match, you know the entire statement fails without testing the remaining characters. In your original code, if any of the characters don't match the first part of the OR statement, you have to check all four characters again in the second part of the OR statement, even the ones you already checked.