-1

I have this code, and I can't see why I cannot use the operator || in this example.

"Operator '||' cannot be applied to operands of type 'bool' and 'int'"

Am I missing something? where is this boolean?

int i = 1;                            
if ( i == 1)
{
    Response.Write("-3");
}
else if (i == 5 || 3) //this is the error, but where is the bool?
{
    Response.Write("-2");
}
PVitt
  • 11,500
  • 5
  • 51
  • 85
LaughingMan
  • 640
  • 1
  • 9
  • 18
  • 4
    Do it like this `else if (i == 5 ||i == 3)` – Anton Gildebrand Apr 22 '12 at 22:14
  • Sorry #2, c#.NET here. and of course, thank you. I haven't been using these tools for months, getting a bit rusty obviously. – LaughingMan Apr 22 '12 at 22:17
  • 1
    The details on your answer depend on your programming language, but the fundamental problem is that you are comparing i == 5 (which will evaluate to a boolean true or false) to 3, which is an int. In some languages, this would work just fine, but probably not in the way you are wanting it to. Anton's comment above probably addresses what you are trying to do. – Marc Talbot Apr 22 '12 at 22:19
  • `5 || 3` is a bool. `i == 5` is a bool. Either way you parse it, it makes no sense. – David Schwartz Apr 22 '12 at 22:20
  • By the way, I'll make sure not to make this noob mistake again, I had misunderstood the datatypes. I will look into it again, but thank you. It works of course with else if (i == 5 ||i == 3) – LaughingMan Apr 22 '12 at 22:21

3 Answers3

3

You need to compare x to y and/or x to z, comparing x to (y or z) isn't allowed in most languages. The bool was introduced when you added the "3" which is an int. The compiler thinks you want (i == 5) || (3) which won't work because 3 does not automatically convert to bool (except maybe in JavaScript).

int i = 1;                            
        if ( i == 1)
        {
            Response.Write("-3");
        }


        else if (i == 5 || i == 3) //this is the error, but where is the bool?
        {
            Response.Write("-2");
        }
Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
2

You can also use a switch-statement. Case 3 And 5 are the same
Example

int i = 1;

        switch (i)
        {
            case 1:
                Response.Write("-3");
                break;
            case 3:
            case 5:
                Response.Write("-2");
                break;
        }

Hope this Helps

Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
Tomtom
  • 9,087
  • 7
  • 52
  • 95
1

The reason why you are getting an error is because you are attempting to perform a boolean evaluation on something doesn't resolve into a boolean equation:

if (false || 3)

Here '3' does not evaluate to a boolean equation.

If you were to change it to

if (false || 3 == 3)

Then you will find that it will work.