Math-Like Chaining of the Comparison Operator - as In, "If ( (5<J<=1) )"

Why multiple if works and if else does not it this case

try

while ((c = getchar()) != EOF)
{
if ('A' <= c && c <= 'Z')
{
++array[c - 'A'];
}
else if ('a' <= c && c <= 'z')
{
++array[c - 'a'];
}
}

'a'<c<'z' is computed not like a mathmatical expression, first 'a' < c is evaluated to True or False then that value (converted to 0 or 1 probably) is compared to 'z', so it is not doing what you are expecting it to.

Why my code outputs false, what happens at if(c b a)?

Operator > is left associative therefore c > b > a will be parenthesize as ((c > b) > a) . Since 30 is greater than 20, c > b = 1. So,

 (c > b) > a => (1 > a) => 1 > 10 => false

Is (4 y 1) a valid statement in C++? How do you evaluate it if so?

The statement (4 > y > 1) is parsed as this:

((4 > y) > 1)

The comparison operators < and > evaluate left-to-right.

The 4 > y returns either 0 or 1 depending on if it's true or not.

Then the result is compared to 1.

In this case, since 0 or 1 is never more than 1, the whole statement will always return false.


There is one exception though:

If y is a class and the > operator has been overloaded to do something unusual. Then anything goes.

For example, this will fail to compile:

class mytype{
};

mytype operator>(int x,const mytype &y){
return mytype();
}

int main(){

mytype y;

cout << (4 > y > 1) << endl;

return 0;
}

Boolean logic evaluation with multiple greater-than operators

It's evaluated left to right. You could have written: (x < y) < z and (z > x) > y.

(x < y) evaluates to 0 or 1, if false or true. This is then compared to the value of z.

To get what you want, you should write:

if ((x > y) && (y > z))

and

if ((z < y) && (y < x))

C++ operator precedence a b c

Do this and please learn the usage of operators beforehand.

if(a<=b && b<c) {
//do stuff
}

What's the most efficient way to test if two ranges overlap?

What does it mean for the ranges to overlap? It means there exists some number C which is in both ranges, i.e.

x1 <= C <= x2

and

y1 <= C <= y2

To avoid confusion, considering the ranges are:
[x1:x2] and [y1:y2]

Now, if we are allowed to assume that the ranges are well-formed (so that x1 <= x2 and y1 <= y2) then it is sufficient to test

x1 <= y2 && y1 <= x2

OR

(StartA <= EndB) and (EndA >= StartB)

Rounding up to next power of 2

Check the Bit Twiddling Hacks. You need to get the base 2 logarithm, then add 1 to that. Example for a 32-bit value:

Round up to the next highest power of 2

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;

The extension to other widths should be obvious.



Related Topics



Leave a reply



Submit