1

I'm currently testing if-statements in C with "not equal" operator with simple variables. But it did not work as expected for some reason and I don't see why. I have tested the "not equal" operators seperatly and it works, but adding them to one single if-statement did not work.

it might be something simple that i'm missing.

int nr1, nr2, nr3;
nr1 = 1;
nr2 = 0;
nr3 = 0;

if (nr1 != 0) {
    printf("nr1 - statement: true");
}
else {
    printf("nr1 - statement: false");
}

printf("\n\n");

if (nr2 != 0) {
    printf("nr2 - statement: true");
}
else {
    printf("nr2 - statement: false");
}

printf("\n\n");

if (nr3 != 0) {
    printf("nr3 - statement: true");
}
else {
    printf("nr3 - statement: false");
}

printf("\n\n");

printf("-----------------------------\n\n");

// if all variables does not contain 0
if (nr1 != 0 || nr2 != 0 || nr3 != 0) {
    printf("if-statement: True\n\n");
    printf("nr1: %d\nnr2: %d\nnr3: %d", nr1, nr2, nr3);
}

//if one variable contain 0
else {
    printf("if-statement: False\n\n");
    printf("%d %d %d", nr1, nr2, nr3);
}
jww
  • 97,681
  • 90
  • 411
  • 885
The Daele
  • 15
  • 4
  • 2
    What is the expected output of your program? What is the actual output? Have you tried [to debug your program](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)? – Some programmer dude Aug 19 '18 at 15:37
  • 1
    Possible duplicate of [How does the compiler evaluate a condition in C](https://stackoverflow.com/questions/31436721/how-does-the-compiler-evaluate-a-condition-in-c) – jww Aug 20 '18 at 06:01

1 Answers1

2

If you want to check // if all variables does not contain 0 then,

This

if (nr1 != 0 || nr2 != 0 || nr3 != 0)

should be

if (nr1 != 0 && nr2 != 0 && nr3 != 0)

Becuase || returns true if any of the operands are true. and && returns true only if all the operands are true.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44