Search code examples
ccomparisonoperators

C-Comparison with multiple variables in a if statement


Hi so i'm new at coding in C and i'd like to know how to compare several variables. Cause my if statement is only working for the first variable and ignore the ||.

scanf("%d %c %d", &nbsaisi, &op, &nbsaisi2); 
if((op != multi) || (op != plus) || (op != moins) || (op!= divi))
   {  
    printf("You haven't entered a valid operator.\n"); 
    exit(1); 
   }

Solution

  • You should enter inside the if block only if all the conditions are met, so in your case your conditions should be in && and not in ||

    if((op != multi) && (op != plus) && (op != moins) && (op!= divi))
       {  
        printf("You haven't entered a valid operator.\n"); 
        exit(1); 
       }