Can you do if ( x < y < z ) fctn1() ; ?

S

sk_usenet

Robert said:
Is that valid C or C++ syntax?
Depends on the types of x, y and z. For integers (that you are probably
assuming) it would compile.
Or must one do x<y && y<z ?

Realize that x<y returns a bool, i.e. true or false. You then compare it
against whatever type "z" has. So the intention of "x<y<z" looks wrong.
 
B

Bo Persson

Robert said:
Is that valid C or C++ syntax?
Or must one do x<y && y<z ?

It actually is valid syntax, but it doesn't do what you want. The
first comparison of "x < y < z" produces a bool result (true or false)
that is then used in the second comparison. Not good.

Stay with the second alternative!


Bo Persson
 
A

alasham.said

Is that valid C or C++ syntax?
Or must one do x<y && y<z ?

Please do not write the main body of the article into the article
title.

As syntax goes the following is correct: if ( x < y < z ) fctn1() ;

however, it may not produce what you expect.

If x, y and z are int values, then x < y evaluates to a bool, is
converted to 0 for false, 1 for true in integral promotion, then
compared to z.

Try the following code. Your compiler should produce appropriate
warnings.

#include <iomanip>
#include <iostream>

int main()
{
std::cout << std::boolalpha << static_cast<bool>( 3 < 2 < 1 ) <<
std::endl;
std::cin.get();
}
 
P

Pascal J. Bourguignon

Robert said:
Is that valid C or C++ syntax?
Or must one do x<y && y<z ?

Despite the negative overlook of the other answers, notice that:

a b a<b (b ==> a) not(b ==> a)
0 < 0 false true false
0 < 1 true false true
1 < 0 false true false
1 < 1 false true false

a<b <=> not(b ==> a)

so:

bool p=x<y<z;

stores in p: not(z ==> x<y)
which may or may not be useful, depending on your problem.

That said, I would define keywords to make it clearer:

#define notimpliedby <
#define impliedby >=
#define implies <=
#define doesnotimply >

so you can write. using parentheses:

int precipitation;
int sunshine;
int temperature_celcius;
if(((precipitation<10)implies(8<sunshine))and(temperature_celcius>20)){
cout<<"Good weather";
}else{
cout<<"Let's go south";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top