C program - trouble with IF statement

AI Thread Summary
The discussion revolves around a user's issue with an "if" statement in a C program that incorrectly prints "a is equal to b" instead of "a is NOT equal to b." Suggestions include using additional brace brackets for clarity and ensuring the correct comparison operator (==) is used instead of the assignment operator (=). The user later resolves the issue by creating a new file and pasting the code, which works correctly. The conversation highlights the importance of debugging and code organization in resolving programming errors. Overall, the problem was resolved, but the cause remained unclear.
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
Messages
4,650
Reaction score
39
I feel silly asking this but I can't get my "If" statement to work correctly. This should print "a is NOT equal to b" but it prints "a is equal to b".
Any help? Thanks!

#include <stdio.h>
int main(void)
{
int a = 10;
int b = 15;

if(a == b)
printf("a is equal to b \n");
else
printf("a is NOT equal to b \n");

return 0;
}
 
Physics news on Phys.org
Try using more brace brackets

#include <stdio.h>
int main(void)
{
int a = 10;
int b = 15;

if(a == b)
{printf("a is equal to b \n");}
else
{printf("a is NOT equal to b \n");}

return 0;
}
 
works for me:

Code:
#include <stdio.h>

int main(void)
{
int a = 10;
int b = 15;

if(a == b)
printf("a is equal to b \n");
else
printf("a is NOT equal to b \n");

return 0; 
}


$ gcc _test.c

$ ./a.exe
a is NOT equal to b
 
Another tip: Make sure you are have a == b and not a = b in the code.
 
One more thing: Get a debugger. You can see what is happening when you step through the code using a debugger than using any other method.
 
e(ho0n3 said:
Another tip: Make sure you are have a == b and not a = b in the code.

I do have double equals. I cut and pasted exactly what I am trying to run.

Thanks.
 
robphy said:
works for me:

bizarre! I create a new.c file and pasted the code back in and now the logic works fine!
I guess it will remain a mystery!

thanks for running that on your end, robphy.
 
AKG said:
Try using more brace brackets

I'll keep that in mind - thanks!
 
Back
Top