-2

I have written the following code, but I can't work out why I am not achieving the expected results.

The program is simply meant to print the value of x. This works fine for numbers 1-5 but when I change x to a number bigger than 5, it prints x does not equal 1 to 5. Can anyone see why this is?

#include <stdio.h>

int main() {
  int x = 3;

  if (x == 1) {
    printf("x equals 1\n");
  } else if (x == 2) {
    printf("x equals 2\n");
  } else if (x == 3, 4, 5) {
    printf("x equals 3, 4 or 5\n");
  } else {
    printf("x does not equal 1 to 5\n");
  }
  return 0;
}
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Ben
  • 3
  • 2
    Where did you get this idea from `(x == 3,4,5)` ? It should be `(x >= 3 && x <= 5)` or `(x == 3 || x == 4 || x == 5)` if you want to be explicit. – Ted Lyngmo Oct 27 '22 at 13:40
  • 1
    `x == 3,4,5` does not mean what you think it means. It should be `x == 3 || x == 4 || x == 5`, or you could use `x >= 3 && x <= 5`. – Ian Abbott Oct 27 '22 at 13:41
  • Hint: `switch`. – tadman Oct 27 '22 at 13:48
  • You need to look up what the comma operator does in C. Barring any side-effects of accessing `x`, `if (x==3,4,5)` is equivalent to `if (5)` and that `if` controlling expression `5` is always true because it never compares equal to `0`. – Ian Abbott Oct 27 '22 at 13:48
  • 2
    Tip: Please, for your own sake, get a [**good C reference**](https://en.cppreference.com/w/c) and keep it on hand *at all times* while learning C. Do not assume C will work a particular way and just bash in some random code and pray it compiles. C is an extremely unforgiving language and will not "do what you mean". – tadman Oct 27 '22 at 13:49
  • @tadman _"pray it compiles"_ you mean _"pray it works"_ ;-) – Jabberwocky Oct 27 '22 at 13:56
  • @Jabberwocky That's the second step in the coding process. – tadman Oct 27 '22 at 14:01

1 Answers1

0

You have to use (x >= 3 && x <= 5) or (x == 3 || x == 4 || x == 5) instead of (x == 3,4,5) in the 13th line in your code.

Usitha Indeewara
  • 870
  • 3
  • 10
  • 21