0

I am writing a Linux driver for my chinese arduino. At one moment I need to change the baud rate. I looked for examples and found that listing:

Listing 2 - Setting the baud rate.

struct termios options;

/*
 * Get the current options for the port...
 */

tcgetattr(fd, &options);

/*
 * Set the baud rates to 19200...
 */

cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);

/*
 * Enable the receiver and set local mode...
 */

options.c_cflag |= (CLOCAL | CREAD);

/*
 * Set the new options for the port...
 */

tcsetattr(fd, TCSANOW, &options);

The next to last line of code has the |= operator. What does it do? I've never seen it before.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
kekyc
  • 317
  • 6
  • 15
  • 1
    `a |= b;` -> `a = a | b;` (with the difference being that `a` is evaluated only once with the `|=` operator, thanks Filipe!) – Kninnug Oct 22 '15 at 22:18
  • `|=` is compound bit-wise `inclusive OR` assignment operator. – haccks Oct 22 '15 at 22:19
  • 3
    @Kninnug This is generally true, but to be technically correct you should mention that `a |= b` is equivalent to `a = a | b` with the exception that `a` is only evaluated once. This is important if the expression `a` has side effects. – Filipe Gonçalves Oct 22 '15 at 22:21
  • Related: [How do you set, clear and toggle a single bit in C/C++?](http://stackoverflow.com/q/47981/119527) – Jonathon Reinhart Oct 23 '15 at 14:34

1 Answers1

3
options.c_cflag |= (CLOCAL | CREAD);

is generally equivalent to

options.c_cflag = options.c_cflag | (CLOCAL | CREAD);

except options.c_cflag is evaluated only once, which doesn't matter in the above expression, but it would matter if options.c_cflag had any side effects (for example, if it were *options.c_cflag++)

PC Luddite
  • 5,883
  • 6
  • 23
  • 39
  • 2
    If you want to make an answer out of this, at least make it complete. Did you read my comment? – Filipe Gonçalves Oct 22 '15 at 22:23
  • If it *were* `options.cflag++`, it'd be undefined behavior. Try `*options.cflagptr++`. – EOF Oct 22 '15 at 22:30
  • @EOF Actually, it wouldn't be undefined behavior, it just won't compile, as `options.c_cflag++` isn't an lvalue. I fixed the answer using your example. – PC Luddite Oct 22 '15 at 22:38