C Compound Assignment

This chapter is from the book 

4.9 Compound Assignment Operators

The compound assignment operators enable you to abbreviate assignment statements. For example, the statement

which mentions the variable on both sides of the assignment, can be abbreviated with the addition assignment operator, as

The operator adds the value of the right operand to the value of the left operand and stores the result in the left operand's variable. Figure 4.8 summarizes the compound assignment operators.

Fig 4.8. Compound assignment operators.

Compound assignment operator

Sample expression

Explanation

Assigns

Assume:

to

to

to

to

to

to

to

The variable on the left side of an assignment operator must be an ("left value")—a modifiable variable or property that can appear on the left side of an assignment statement. We'll learn how to declare constants in Section 6.10—constants cannot be lvalues.

The , , , , , , and operators are always applied last in an expression. When an assignment () is evaluated, the expression to the right of the operator is always evaluated first, then the value is assigned to the lvalue on the left. When a compound assignment is evaluated, the appropriate operator is applied to the lvalue's original value and the value to the operator's right, then the resulting value is assigned to the lvalue on the left.

Demonstrating the ^= Compound Assignment Operator

Figure 4.9 calculates a power of 2 using the exponentiation assignment operator. In line 8, we take advantage of a Visual Basic feature that allows variable initialization to be incorporated into a declaration. In this case, we initialize variable to the value of 's property. Lines 12 and 17 each raise variable to the value of variable . The results of these two calculations are identical as shown in the sample output.

Fig 4.9. Exponentiation using a compound assignment operator.

1' Fig. 4.9: PowerOf2.vb2' Calculates 2 raised to the exponent entered by the user.3Public Class PowerOf2 4' calculates 2 raised to the exponent entered by the user.5Private Sub calculateButton_Click(ByVal sender As System.Object, 6ByVal e As System.EventArgs) Handles calculateButton.Click 78Dim exponent As Integer = exponentTextBox.Text ' get the exponent9Dim result As Integer' stores the calculation result1011 result = 2' number to raise to a power1213 resultLabel.Text = "result = 2" & vbCrLf & 14"result ^= " & exponent & ": " & result & vbCrLf & vbCrLf1516 result = 2' reset result to 2 for next calculation1718 resultLabel.Text &= "result = 2" & vbCrLf & 19"result = result ^ " & exponent & ": " & result 20End Sub' calculateButton_Click2122' clear results when user types in the exponentTextBox23Private Sub exponentTextBox_TextChanged(ByVal sender As System.Object, 24ByVal e As System.EventArgs) Handles exponentTextBox.TextChanged 25 resultLabel.Text = String.Empty' clears the resultLabel's text26End Sub' exponentTextBox_TextChanged27End Class' PowerOf2

This is a list of operators in the C and C++programming languages. All the operators listed exist in C++; the fourth column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.

When not overloaded, for the operators , , and (the comma operator), there is a sequence point after the evaluation of the first operand.

C++ also contains the type conversion operators , , , and . The formatting of these operators means that their precedence level is unimportant.

Most of the operators available in C and C++ are also available in other languages such as C#, D, Java, Perl, and PHP with the same precedence, associativity, and semantics.

Table[edit]

For the purposes of these tables, , , and represent valid values (literals, values from variables, or return value), object names, or lvalues, as appropriate. , and stand for any type(s), and for a class type or enumerated type.

Arithmetic operators[edit]

Operator nameSyntaxCan overload in C++Included
in C
C++ Prototype examples
As member of KOutside class definitions
Basic assignmentYesYesN/A
AdditionYesYes
SubtractionYesYes
Unary plus (integer promotion)YesYes
Unary minus (additive inverse)YesYes
MultiplicationYesYes
DivisionYesYes
Modulo (integer remainder)[a]YesYes
IncrementPrefixYesYes
PostfixYesYes
Note: C++ uses the unnamed dummy-parameter to differentiate between prefix and postfix increment operators.
DecrementPrefixYesYes
PostfixYesYes
Note: C++ uses the unnamed dummy-parameter to differentiate between prefix and postfix decrement operators.

Comparison operators/relational operators[edit]

   Operator name     Syntax Can overload in C++Included
in C
Prototype examples
As member of KOutside class definitions
Equal toYesYes
Not equal to
[b]
YesYes
Greater thanYesYes
Less thanYesYes
Greater than or equal toYesYes
Less than or equal toYesYes

Logical operators[edit]

Operator name  Syntax  Can overload in C++Included
in C
Prototype examples
As member of KOutside class definitions
Logical negation (NOT)
[b]
YesYes
Logical AND
[b]
YesYes
Logical OR
[b]
YesYes

Bitwise operators[edit]

Operator name  Syntax  Can overload in C++Included
in C
Prototype examples
As member of KOutside class definitions
Bitwise NOT
[b]
YesYes
Bitwise AND
[b]
YesYes
Bitwise OR
[b]
YesYes
Bitwise XOR
[b]
YesYes
Bitwise left shift[c]YesYes
Bitwise right shift[c][d]YesYes

Compound assignment operators[edit]

Operator name  Syntax      Meaning    Can overload in C++Included
in C
Prototype examples
As member of KOutside class definitions
Addition assignmentYesYes
Subtraction assignmentYesYes
Multiplication assignmentYesYes
Division assignmentYesYes
Modulo assignmentYesYes
Bitwise AND assignment
[b]
YesYes
Bitwise OR assignment
[b]
YesYes
Bitwise XOR assignment
[b]
YesYes
Bitwise left shift assignmentYesYes
Bitwise right shift assignment[d]YesYes

Member and pointer operators[edit]

Operator nameSyntaxCan overload in C++Included
in C
Prototype examples
As member of KOutside class definitions
SubscriptYesYes
N/A
Indirection ("object pointed to by a")YesYes
Address-of ("address of a")YesYes
Structure dereference ("member b of object pointed to by a")YesYes[e]
N/A
Structure reference ("member b of object a")NoYesN/A
Member selected by pointer-to-memberb of object pointed to by a[f]YesNo
Member of object a selected by pointer-to-memberbNoNoN/A

Other operators[edit]

Operator nameSyntaxCan overload in C++Included
in C
Prototype examples
As member of KOutside class definitions
Function call
See Function object.
YesYesN/A
CommaYesYes
Ternary conditionalNoYesN/A
Scope resolutionNoNoN/A
User-defined literals[g]
since C++11
YesNoN/A
Size-of[h]
NoYesN/A
Size of parameter pack
since C++11
NoNoN/A
Align-of
since C++11

or [i]
NoYesN/A
Type identification
NoNoN/A
Conversion (C-style cast)NoYesN/A
ConversionNoNoNote: behaves like const_cast/static_cast/reinterpret_cast[2]
static_cast conversionYesNo
since C++11
N/A
Note: for user-defined conversions, the return type implicitly and necessarily matches the operator name.
dynamic cast conversionNoNoN/A
const_cast conversionNoNoN/A
reinterpret_cast conversionNoNoN/A
Allocate storageYesNo
Allocate storage (array)YesNo
Deallocate storageYesNo
Deallocate storage (array)YesNo
Exception check
since C++11
NoNoN/A

Notes:

Operator precedence[edit]

The following is a table that lists the precedence and associativity of all the operators in the C and C++ languages (when the operators also exist in Java, Perl, PHP and many other recent languages, the precedence is the same as that given[citation needed]). Operators are listed top to bottom, in descending precedence. Descending precedence refers to the priority of the grouping of operators and operands. Considering an expression, an operator which is listed on some row will be grouped prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are grouped with the same precedence, in the given direction. An operator's precedence is unaffected by overloading.

The syntax of expressions in C and C++ is specified by a phrase structure grammar.[3] The table given here has been inferred from the grammar.[citation needed] For the ISO C 1999 standard, section 6.5.6 note 71 states that the C grammar provided by the specification defines the precedence of the C operators, and also states that the operator precedence resulting from the grammar closely follows the specification's section ordering:

"The [C] syntax [i.e., grammar] specifies the precedence of operators in the evaluation of an expression, which is the same as the order of the major subclauses of this subclause, highest precedence first."[4]

A precedence table, while mostly adequate, cannot resolve a few details. In particular, note that the ternary operator allows any arbitrary expression as its middle operand, despite being listed as having higher precedence than the assignment and comma operators. Thus is interpreted as , and not as the meaningless . Also, note that the immediate, unparenthesized result of a C cast expression cannot be the operand of . Therefore, is interpreted as and not .

PrecedenceOperatorDescriptionAssociativity
1

highest

Scope resolution (C++ only)None
2Postfix incrementLeft-to-right
Postfix decrement
Function call
Array subscripting
Element selection by reference
Element selection through pointer
Run-time type information (C++ only) (see typeid)
Type cast (C++ only) (see const_cast)
Type cast (C++ only) (see dynamic cast)
Type cast (C++ only) (see reinterpret_cast)
Type cast (C++ only) (see static_cast)
3Prefix incrementRight-to-left
Prefix decrement
Unary plus
Unary minus
Logical NOT
Bitwise NOT (One's Complement)
Type cast
Indirection (dereference)
Address-of
Size-of
, Dynamic memory allocation (C++ only)
, Dynamic memory deallocation (C++ only)
4Pointer to member (C++ only)Left-to-right
Pointer to member (C++ only)
5MultiplicationLeft-to-right
Division
Modulo (remainder)
6AdditionLeft-to-right
Subtraction
7Bitwise left shiftLeft-to-right
Bitwise right shift
8Less thanLeft-to-right
Less than or equal to
Greater than
Greater than or equal to
9Equal toLeft-to-right
Not equal to
10Bitwise ANDLeft-to-right
11Bitwise XOR (exclusive or)Left-to-right
12Bitwise OR (inclusive or)Left-to-right
13Logical ANDLeft-to-right
14Logical ORLeft-to-right
15Ternary conditional (see ?:)Right-to-left
16Direct assignmentRight-to-left
Assignment by sum
Assignment by difference
Assignment by product
Assignment by quotient
Assignment by remainder
Assignment by bitwise left shift
Assignment by bitwise right shift
Assignment by bitwise AND
Assignment by bitwise XOR
Assignment by bitwise OR
17Throw operator (exceptions throwing, C++ only)Right-to-left
18

lowest

CommaLeft-to-right

[5]

Notes[edit]

The precedence table determines the order of binding in chained expressions, when it is not expressly specified by parentheses.

  • For example, is ambiguous without some precedence rule(s). The precedence table tells us that: is 'bound' more tightly to than to , so that whatever does (now or later—see below), it does it ONLY to (and not to ); it is equivalent to (, ).
  • Similarly, with , where though the post-fix is designed to act AFTER the entire expression is evaluated, the precedence table makes it clear that ONLY gets incremented (and NOT ). In fact, the expression (, ) is evaluated with being a temporary value. It is functionally equivalent to something like (, , ).
  • Abstracting the issue of precedence or binding, consider the diagram above for the expression 3+2*y[i]++. The compiler's job is to resolve the diagram into an expression, one in which several unary operators (call them 3+( . ), 2*( . ), ( . )++ and ( . )[ i ]) are competing to bind to y. The order of precedence table resolves the final sub-expression they each act upon: ( . )[ i ] acts only on y, ( . )++ acts only on y[i], 2*( . ) acts only on y[i]++ and 3+( . ) acts 'only' on 2*((y[i])++). It is important to note that WHAT sub-expression gets acted on by each operator is clear from the precedence table but WHEN each operator acts is not resolved by the precedence table; in this example, the ( . )++ operator acts only on y[i] by the precedence rules but binding levels alone do not indicate the timing of the postfix ++ (the ( . )++ operator acts only after y[i] is evaluated in the expression).

Many of the operators containing multi-character sequences are given "names" built from the operator name of each character. For example, and are often called plus equal(s) and minus equal(s), instead of the more verbose "assignment by addition" and "assignment by subtraction". The binding of operators in C and C++ is specified (in the corresponding Standards) by a factored language grammar, rather than a precedence table. This creates some subtle conflicts. For example, in C, the syntax for a conditional expression is:

logical-OR-expression?expression:conditional-expression

while in C++ it is:

logical-OR-expression?expression:assignment-expression

Hence, the expression:

e = a < d ? a++ : a = d

is parsed differently in the two languages. In C, this expression is a syntax error, because the syntax for an assignment expression in C is:

unary-expression'='assignment-expression

In C++, it is parsed as:

e=(a<d?a++:(a=d))

which is a valid expression.

Criticism of bitwise and equality operators precedence[edit]

The precedence of the bitwise logical operators has been criticized.[6] Conceptually, & and | are arithmetic operators like * and +.

The expression is syntactically parsed as whereas the expression is parsed as . This requires parentheses to be used more often than they otherwise would.

Historically, there was no syntactic distinction between the bitwise and logical operators. In BCPL, B and early C, the operators didn't exist. Instead had different meaning depending on whether they are used in a ‘truth-value context’ (i.e. when a Boolean value was expected, for example in it behaved as a logical operator, but in it behaved as a bitwise one). It was retained so as to keep backward compatibility with existing installations.[7]

Moreover, in C++ (and later versions of C) equality operations yield bool type values which are conceptually a single bit (1 or 0) and as such do not properly belong in "bitwise" operations.

C++ operator synonyms[edit]

C++ defines[8] certain keywords to act as aliases for a number of operators:

  1. ^The modulus operator works just with integer operands, for floating point numbers a library function must be used instead (like ).
  2. ^ abcdefghijkRequires in C. See C++ operator synonyms
  3. ^ abIn the context of iostreams, writers often will refer to and as the "put-to" or "stream insertion" and "get-from" or "stream extraction" operators, respectively.
  4. ^ abAccording to the C99 standard, the right shift of a negative number is implementation defined. Most implementations, e.g., the GCC,[1] use an arithmetic shift (i.e., sign extension), but a logical shift is possible.
  5. ^The return type of must be a type for which the operation can be applied, such as a pointer type. If is of type where overloads , gets expanded to .
  6. ^Meyers, Scott (Oct 1999), "Implementing operator->* for Smart Pointers"(PDF), Dr.Dobbs, Aristeia .
  7. ^About C++11 User-defined literals
  8. ^The parentheses are not necessary when taking the size of a value, only when taking the size of a type. However, they are usually used regardless.
  9. ^C++ defines operator, whereas C defines . Both operators have the same semantics.

0 thoughts on “C Compound Assignment”

    -->

Leave a Comment

Your email address will not be published. Required fields are marked *