1

Sorry if this has been asked before or is a stupid question, but I'm new to both the site and C. So, when I run this code, when I type an answer, any answer, be it right or wrong, it says what it's supposed to say when for the if statement.

Here's the code:

#include <stdio.h>
int main()
{
    int x;
    printf("1+1=");
    scanf("%d", &x);
    if("x==2"){
        printf("Watch out, we got a genius over here!");
    }
    else {
        printf("I don't even know what to say to this...");
    }
    return 0;
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 7
    `if(x==2){` ... – Raptor Oct 18 '13 at 02:35
  • 5
    "Watch out, we got a genius over here!" - a rather unfortunate output statement. – Mitch Wheat Oct 18 '13 at 02:37
  • 2
    Welcome to Stack Overflow. Please read the [About] page soon. The `if` condition as written tests whether the pointer to the string `"x==2"` is a null pointer, and it isn't, so the `if` always evaluates to true. Hence, as everyone else said, you need to remove the quotes around `x == 2`. Also, it is a good idea to print a newline at the end of each line of output. – Jonathan Leffler Oct 18 '13 at 02:38

4 Answers4

10

you need

if(x==2) 

without the quotes

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
3

try this

#include <stdio.h>
int main()
{
int x;
printf("1+1=");
scanf("%d", &x);
if(x==2){
    printf("Watch out, we got a genius over here!");
}
else {
    printf("I don't even know what to say to this...");
}
return 0;
}
Baahubali
  • 4,604
  • 6
  • 33
  • 72
3

try

#include <stdio.h>
int main()
{
    int x;
    printf("1+1=");
    scanf("%d", &x);
    //modify this line if("x==2"){
    if(x==2){
        printf("Watch out, we got a genius over here!");
    }
    else {
        printf("I don't even know what to say to this...");
    }
    return 0;
}
sunysen
  • 2,265
  • 1
  • 12
  • 13
1

"x==2" is a string literal of type const char* that lies in memory and has an address. Addresses to real objects in C are never 0§ so the expression is always true and the else branch will never be taken


§Although some architecture (most notably embedded systems) may have a non-zero bit pattern for NULL pointer, but C requires them to compare equal to zero constant. See When was the NULL macro not 0?

phuclv
  • 37,963
  • 15
  • 156
  • 475