This question already has an answer here:
Why doesn't C++ have the ~= and != operators? [closed]
(1 answer)
Closed 5 years ago.
int main()
{
unsigned int a = 0;
unsigned int b = 0;
a ^= b; // ok
a |= b; // ok
a &= b; // ok
a = ~b; // ok
a ~= b; // error : expected ';' after expression
}
^=, |=, and &= are all legal.
Why isn't ~= legal in C++?
Because ~ is an unary operator, not binary.
The short form op= applies to binary operators only, when the first operand is the destination.
~ is only ever a unary operator.
The contraction of a = a # b to a #= b for an arbitrary operator # only makes sense if it takes two arguments; i.e. if # is a binary operator.
Why isn't ~= legal in C++?
That's because C++ does not contain an ~= operator; ~= are just two separate tokens.
As for why C++ wasn't designed that way, you'd have to ask the designer, but I think it's safe to say that it's because C++ was based on C originally and has the same operators as C, with only a few new operators added for the new language features (i.e. :: and ->*).
So you should probably ask this question again for C.
Because the "operator assignments" (like +=, ^=) are based on the original operation having two operands.
For example, a + b has two operands of +, and a += b gives the same net effect as a = a + b.
Operator ~ is a unary operator i.e. it accepts one operand. So a = ~b makes sense, but a = a~b does not. Since a = a~b doesn't make sense, neither does a ~= b.
Related
Neither cppreference nor cplusplus, and nor Microsoft websites provided the verbose definition of the C++ keyword &= (a.k.a. and_eq), despite examples that seem to be a bit cryptic for a novice.
Yet the book C++ In a Nutshell: A Desktop Quick Reference by Lischner provided the following (p. 291, 2003):
The and_eq operator is an assignment operator that performs bitwise and.
Quoting the example from Microsoft:
#include <iostream>
#include <iso646.h>
int main( )
{
using namespace std;
int a = 3, b = 2, result;
result= a &= b;
cout << result << endl;
}
yields 2.
Accordingly, could you please tell me whether &= is a shortcut for concatenated assignments (if such a thing exists?), for example: result = a = b;?
No. a &= b is a shortcut for a = a & b.
Additionally, a = b returns the value that was assigned to a. So result = a &= b is short for:
a = a & b;
result = a;
&=, and all of the other op= built in operators are described in [expr.ass]\7 as
The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.
So, result= a &= b; is the same as
result = (a = (a & b));
or textually:
store the result of bitwise and between a and b into a and result.
It's not a keyword, it's an expression operator. Found here: https://en.cppreference.com/w/cpp/language/expressions
It is the bit-wise AND operator combined with the assignment operator. On primitive types, it performs a bit-wise AND on the two parameters and then assigns the result to the first parameter.
uint32_t a = 0b00110101;
uint32_t b = 0b01101011;
a &= b;
//Equivalent: a = a & b;
assert(a == 0b00100001);
foo &= bar is short for foo = foo & bar, for built-in types. But, it's an operator that can be reimplemented by user defined types, so it's semantics could be changed for such.
There’s one relevant difference between a = a & b; and a &= b;. The former creates a temporary equal to a & b and assigns that temporary value to a. The latter updates a in place.
For built-in types, that doesn’t matter: any compiler will just optimize either expression to the same machine-language instruction. If you define a class and overload the operators, though, writing a = a & b; might end up creating a temporary object, copying a bunch of data to it, and then copying all its data somewhere else. While there are ways to mitigate this problem, a &= b; is in theory more efficient.
I am new to c++ and haven't seen such a declaration in programs anywhere. Please help me
For integral type
i >>= 3;
is equal to:
i = i >> 3;
ie bitwise shift variable i right (in his case) in place.
For user defined classes it can be overloaded to whatever functionality author wants this operator to implement
Use of compound assignment operators is encouraged since it evaluates the LHS only once.
From the C++11 Standard:
5.17 Assignment and compound assignment operators
...
7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.
If you have a function that returns a reference to an object, it is more efficient and less error prone when you use a compound assignment operator.
E.g.
std::vector<int> v(10, 1);
v[4] <<= 2;
is better than
std::vector<int> v(10);
v[4] = v[4] << 2;
those are called compound assignment operators. There are almost 10 of them in C/C++ language. ex += -= *= <<= >>=. When one of the operand is same as the variable to which final result to be assigned is same, in a binary operation this can be used as a short hand syntax. Ex a=a+b can be written as a+=b. in the same a=a<<2 can be written as a<<=2. This type of syntactic sugar is also supported by other languages too.
Left shift assignment <<=
x <<= y Shift x left by y bits
Right shift assignment >>=
x >>= y Shift x right by y bits
Read This to know more about bitwise operators in c++.
In c in general, an operator with an equals following it is shorthand for "do the operation, and put the result back in the same variable."
x = x >> 4; // shift x right by 4 bits
x >>= 4; // exactly the same as above
x <<= 3; // shift x left by 3 bits
This assumes that x is a numeric type like long, unsigned short, etc.
If x is not numeric, then the original programmer probably defined the operation as an overloaded operator in c++, for example, lopping off n characters from a string.
This question already has answers here:
Errors using ternary operator in c
(5 answers)
Closed 8 years ago.
There are a lot of differences between C and C++ and came to stuck on one of them
The same code gives an error in C while just executes fine in C++
Please explain the reason
int main(void)
{
int a=10,b;
a>=5?b=100:b=200;
}
The above code gives an error in C stating lvalue required while the same code compiles fine in C++
Have a look at the operator precedence.
Without an explicit () your code behaves like
( a >= 5 ? b = 100 : b ) = 200;
The result of a ?: expression is not a modifiable lvalue [#] and hence we cannot assign any values to it.
Also, worthy to mention, as per the c syntax rule,
assignment is never allowed to appear on the right hand side of a conditional operator
Relared Reference : C precedence table.
OTOH, In case of c++, well,
the conditional operator has the same precedence as assignment.
and are grouped right-to-left, essentially making your code behave like
a >= 5 ? (b = 100) : ( b = 200 );
So, your code works fine in case of c++
[ # ] -- As per chapter 6.5.15, footnote (12), C99 standard,
A conditional expression does not yield an lvalue.
Because C and C++ aren't the same language, and you are ignoring the assignment implied by the ternary. I think you wanted
b = a>=5?100:200;
which should work in both C and C++.
In C you can fix it with placing the expression within Parentheses so that while evaluating the assignment becomes valid.
int main(void)
{
int a=10,b;
a>=5?(b=100):(b=200);
}
The error is because you don't care about the operator precedence and order of evaluation.
This question already has answers here:
What does the operation c=a+++b mean?
(9 answers)
Why doesn't a+++++b work?
(9 answers)
Closed 9 years ago.
Given the following code:
int a=0,b=1;
int r=a+++b;
which are the operations performed and in which order?
a++ + b
a + ++b
I this compiler specific or does it depend on the standard?
It is (a++) + b but not because of operator precedence.
It is parsed as (a++) + b because the compiler takes the longest token it can from a sequence of characters. In other words, the lexer keeps reading characters until it encounters something that can't be part of the same token as what it already has.
This is also how it interprets >= as one token instead of > and =, and double as 'double' not 'do uble'.
There are rules of operator precedence for statements like
a || b && c
// "a || (b && c)" NOT "(a || b) && c", because && takes precedence
However, in your case the operators ++ and + have already been determined. Once the operators have been determined, the rules of operator precedence can apply.
There are some good answers to Why doesn't a+++++b work in C? that should explain this in more detail.
That is governed by the operator precedence. Since postfix ++ has a higher precedence than the + operator it binds tighter to a is post incremented then added to b so the result is:
(a++) + b
This question already has answers here:
What's the result of += in C and C++?
(2 answers)
Closed 9 years ago.
I'm surprised that this works:
double x = 3;
double y = 2;
(x *= 2) += y;
std::cout << x << std::endl;
The result is 8, which is what it looks like the programmer is trying to achieve. But I thought assignment operators returned an rvalue - how is it that you can assign to the result of one?
The assignment operators for the built in types return an lvalue
in C++ (unlike in C). But you cannot use it to modify the
object without an intervening sequence point, so your example is
undefined behavior (in C++03—C++11 changed a lot here, and
I seem to remember that one of the results made your code
defined).
Regardless of the situation with regards to undefined behavior,
you would be better off writing:
x = 2 * x + y;
It's far more readable. The fact that the assignment operators
result in lvalues is really only usable when the results are
bound immediately to a reference:
T&
SomeClass::f()
{
// ...
return aTinSomeClass += 42;
}
And even then, I'd write it in two statements.
(The general rule in C++ is that if the result of an operator
corresponds to the value of an object in memory, then it is an
lvalue. There was no general rule in C.)
In C++ the result of the assignment operators, including the compound assignment operators (such as *=) are l-values, and thus assignables.
In C they are r-values, so your code invalid C code.
In C++, compound assignment operators return lvalues, as per §5.17/1:
The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.
In this case, the use of *= returns an lvalue denoting the object x which is then used as the left operand of the += operator.
Perhaps you are thinking of the simple arithmetic operators like + and * which do return rvalues.
In C, these operators don't return lvalues and therefore the result can't be further assigned.