0

Disclaimer: I'm a newbie. I was trying out conditional chains in C with a simple quiz.

I entered this:

int age = get_int("Age in whole numbers: ");

        int r;
        if(age<12)
        {
            printf("Go back kid\n");
            r = 0;
        }
        else if(12<= age <16)
        {
            printf("Teenagers not allowed\n");
            r = 0;
        }

(im using cs50 codespace in visualstudio which has aforementioned get_int function)

age<12 worked but problem showed with this line

  else if(12<= age <16)

The error mentioned in title: Error

My main question is the "why" and not just the "how" - as in how does this result in a "Boolean expression" in this case?? I just want to check if age is greater than or equal to 12, and less than 16. The age variable is declared int and will store an int and not Boolean as per my current understanding. How else do I compare the variable input?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Astha
  • 9
  • 1

3 Answers3

1

You want

12 <= age && age < 16

or

age >= 12 && age < 16

12 <= age < 16

means

( 12 <= age ) < 16

12 <= age is 0 or 1 depending on the value of age, so you end up with

0 < 16

or

1 < 16

So your condition is always true.

ikegami
  • 367,544
  • 15
  • 269
  • 518
0

You cannot write "math-style" comparisons, the comparison operators are strictly binary (compare two things, left-hand and right-hand sides) so you end up doing

else if ((12 <= age) < 16)

since the first <= results in 0 or 1, it's always less than 16 which is always true.

Instead I would write it as:

else if (age >= 12 && age < 16)

I think that's easier to read, with the variable on the left on both comparisons.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

12 <= age is a 'boolean expression', which means it will convert 12 <= age to a boolean (true or false). In C false = 0 and true = 1. So if you write it differently:

  1. (12 <= age < 16)
  2. (true < 16) or (false < 16)
  3. (1 < 16) or (0 < 16)
  4. true or true

What you have to do is split it up into the individual expressions.

(12<= age <16) --> (12 <= age && age < 16)

GRASBOCK
  • 631
  • 6
  • 16