What does the vertical bar ( | ) mean in C++?
Asked Answered
B

4

23

I have this C++ code in one of my programming books:

WNDCLASSEX wndClass = { 0 };
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style =  CS_HREDRAW | CS_VREDRAW;

What does the single pipe do in C++ windows programming?

Bosket answered 15/4, 2012 at 16:56 Comment(2)
This has nothing to do with windows programming; this is a basic operator of C++.Theona
Actually it is a operator of C, C++ adopts itEpisode
N
36

Bitwise OR operator. It will set all bits true that are true in either of both values provided.

For example CS_HREDRAW could be 1 and CS_VREDRAW could be 2. Then it's very simple to check if they are set by using the bitwise AND operator &:

#define CS_HREDRAW 1
#define CS_VREDRAW 2
#define CS_ANOTHERSTYLE 4

unsigned int style = CS_HREDRAW | CS_VREDRAW;
if(style & CS_HREDRAW){
    /* CS_HREDRAW set */
}

if(style & CS_VREDRAW){
    /* CS_VREDRAW set */
}

if(style & CS_ANOTHERSTYLE){
    /* CS_ANOTHERSTYLE set */
}

See also:

Nonjoinder answered 15/4, 2012 at 16:58 Comment(2)
whaa..? all bits to true? so let me think. 010101 | 101010 would return 111111?Bosket
Yes. b00010101 | b00101010 will return b00111111.Nonjoinder
M
13

In C++20, it can also be the pipe operator of range adaptor closure objects. I.e. chaining together operations on ranges. Read more about it here: https://en.cppreference.com/w/cpp/ranges#Range_adaptor_closure_objects

Monocular answered 20/5, 2022 at 6:46 Comment(1)
github.com/ReactiveX/RxCpp check it outReedbuck
B
11

| is called bitwise OR operator.

|| is called logical OR operator.

Bifocals answered 15/4, 2012 at 16:57 Comment(0)
J
6

It's a bitwise OR operator. For instance,

if( 1 | 2 == 3) {
    std::cout << "Woohoo!" << std::endl;
}

will print Woohoo!.

Joinville answered 15/4, 2012 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.