Topic: Proposal: Strongly Typed Logical Operators "and", "or" and "not


Author: "msalters" <Michiel.Salters@logicacmg.com>
Date: Tue, 5 Apr 2005 13:30:30 CST
Raw View
Marc Schoolderman wrote:
> Richard Kaiser wrote:
>
> > Current Boolean operators "and", "or" and "not" (like
&&, || and !) are
> > not type-safe. Since their operands are subject to integral
promotions,
> > expressions like
> >
> >     int i; bool b;
> >     if (b and i) ...
> >     if (b or i) ...
> >     if (not i) ...
> >
> > are valid, although they may not be intended.
>
> My understanding of "and", "or" and "not", just like the keywords
'xor',
> 'bitand', 'bitor' and so on was that they are 100% synonyms

Correct. In fact, they're so identical that defining bool
  X::operator and(X)
allows one to write
  X a,b;
  a&&b;
and vice versa, declaring operator&& allows (a and b). Breaking that
relation breaks existing code, for a very limited improvement if any.

Also, C++ has a tradition of considering non-bools as bools:
if( p && p->x )...
while( std::cin >> tmp ) ...

Conclusion: won't fly.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: richard@ex-parrot.com
Date: Tue, 5 Apr 2005 13:32:29 CST
Raw View
Richard Kaiser wrote:
>
> Since the alternative tokens "and", "or" and "not" are
not widely used

Perhaps not *widely* used, but they are certain in use.

Francis Glassborow's introductory book on C++ uses "not" quite a bit,
and, in my opinion, "not" often improves the readability of code.  I
expect in the future we'll see more C++ programmers who learnt from
this book, and then we'll see heavier use of these alternative tokens.

Having used these alternative tokens in Perl quite a while before
encountering them in C++, I do sometimes get caught out by their
precedences.  In Perl, &&, || and ! have the same precedences as in
C++; however, the alternative tokens, "and", "or" and "not", have lower
precedences.  This allows more idiomatic expressions in Perl such as

  a = foo() or die "Foo failed" ;

where "die" is a bit like "throw" in C++ and the "or" binds less
tightly than the assignment.

I don't think it's feasible to do anything about this in C++ -- I'm not
even sure it's desireable -- but it is an obvious gotcha for Perl
programmers coming to C++.

--
Richard Smith

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]