简体   繁体   中英

C++ Bars in function parameters

int fd = open(JOYSTICK_NAME, O_RDONLY | O_NONBLOCK);

What does the bar between O_RDONLY and O_NONBLOCK mean? I've encountered this in OpenGL/GLUT programming and I was curious on the semantics.

This is the bitwise OR operator . It takes the individual bits in O_RDONLY and combines them with the bits in O_NONBLOCK , and returns the combined value.

For example, suppose the binary value for O_RDONLY is 11001100 and the binary value for O_NONBLOCK is 00001111. OR-ing these together yields 11001111.

It's the bitwise-or operator. It's used to accumulate bitflags.

It is a bitwise OR of the two operands. In this case the operands are both defined in fcntl.h :

/* File access modes for open() and fcntl().  POSIX Table 6-6. */
#define O_RDONLY           0    /* open(name, O_RDONLY) opens read only */
#define O_WRONLY           1    /* open(name, O_WRONLY) opens write only */
#define O_RDWR             2    /* open(name, O_RDWR) opens read/write */
...
/* File status flags for open() and fcntl().  POSIX Table 6-5. */
#define O_APPEND       02000    /* set append mode */
#define O_NONBLOCK     04000    /* no delay */

So O_RDONLY :

000 000 000 000  (0) 

is ORed with O_NONBLOCK :

100 000 000 000  (04000 in octal notation)

The result is therefore:

100 000 000 000  (0400)

Not a very exciting example, but that's what it is doing...

那是按位或运算

That is a bitwise OR. It takes the binary representation of the two arguments (O_RDONLY and O_NONBLOCK) and applies the OR operation to them, returning the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM