0

I have code line

int i =0;
result |= EXPECT_EQUAL(list.size(),     3);

What does |= mens?

I was trying to compile something like:

int result |= 5;

but got error:

aaa.cpp:26:16: error: expected initializer before ‘|=’ token
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

35

a |= b; is just syntactic sugar for a = a | b;. Same syntax is valid for almost every operator in C++.

But int i |= 5; is an error, because in the definition line you must have an initialisation, that is an expression that does not use the variable being declared.

int i=3;
i |= 5;

is valid and will give value 7 (3 | 5) to i.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • 1
    While `a |= b;` and `a = a | b;` produce the same result, [they are not strictly equal](https://programmers.stackexchange.com/questions/134118/why-are-shortcuts-like-x-y-considered-good-practice) in terms of implementation. – Cory Kramer Aug 09 '15 at 15:44
  • The implementation may be different or may be the same at the choice of the compiler... anyway implementation and the various optimizations are not defined by the standard – Serge Ballesta Aug 09 '15 at 15:48
  • 2
    @CoryKramer: That's nonsense; the accepted answer there is mired in history and low-level implementation specifics; the operations, per the _language_, are in fact entirely equivalent. At least it's correct in admitting that the two will compile to the same code. – Lightness Races in Orbit Aug 09 '15 at 16:16
10

It's the operator for assignment by bitwise OR.

http://en.cppreference.com/w/cpp/language/operator_assignment

int result |= 5;

You cannot initialize an int and assign something to it at the same time. Initialization and assignment are different things. You'd have to write:

int result = 0;
result |= 5;

If this is what you intend, of course. Since int result |= 5; is not C++, we can only guess about your intention.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62