Domanda

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;
}
È stato utile?

Soluzione

you need

if(x==2) 

without the quotes

Altri suggerimenti

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

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top