DEV Community

Swastik Baranwal
Swastik Baranwal

Posted on • Updated on

Modern C++ : `and`, `or` and `not` as Boolean Operators

Following my series from less known features of Modern C++.

In Modern C++, you can also use and, or and not as boolean operators which means &&, || and ! respectively which is identical to languages like Python. They were in C but as macros but Modern C++ introduced them as keywords.

#include <iostream>

int main() {

std::cout << true and true << std::endl;
std::cout << true or false << std::endl;
std::cout << not true << std::endl;

 return 0;
}
Enter fullscreen mode Exit fullscreen mode

This is exactly identical to.

#include <iostream>

int main() {

std::cout << true && true << std::endl;
std::cout << true || false << std::endl;
std::cout << !true << std::endl;

 return 0;
}
Enter fullscreen mode Exit fullscreen mode

You can probably use any one of the styles depending on your codebase.

Top comments (4)

Collapse
 
idanarye profile image
Idan Arye

Why would they even do that? Even if you are not a pedantic preacher of the only-one-way-to-do-it philosophy, there should at least be a reason for having multiple ways to do it...

Collapse
 
larzhino profile image
Larz

It's really disingenuous to label this "Modern" C++. It's a legacy C feature to support keyboards that didn't have all the previously accepted symbols (en.wikipedia.org/wiki/Digraphs_and...) or to make it more accessible for people with trouble inputting all the symbols.

Collapse
 
safijari profile image
Jariullah Safi

Heh, that's funny. One of my colleagues once went on an angry tirade about how "modern" C++ was ruining programming by allowing you to have a one statement if block without any surrounding curly braces...

I didn't have the heart to tell him...

Collapse
 
darthwalsh profile image
Carl Walsh

Interesting, I knew about trigraphs but apparently they went away in C++17. and isn't strictly a C language feature: it's a language keyword in C++ but is a macro in C.

Here's more docs on the and/or/not alternative operators: en.cppreference.com/w/cpp/language...