Desmond Pearce
Desmond Pearce

Reputation: 21

Why does my if statement work, but my else doesn't?

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;
}

Upvotes: 1

Views: 343

Answers (4)

phuclv
phuclv

Reputation: 41804

"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?

Upvotes: 1

sunysen
sunysen

Reputation: 2351

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;
}

Upvotes: 3

Baahubali
Baahubali

Reputation: 4802

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;
}

Upvotes: 3

Keith Nicholas
Keith Nicholas

Reputation: 44298

you need

if(x==2) 

without the quotes

Upvotes: 10

Related Questions