Compound Assignment Operators In Ansi Code

Java Assignment Operators

Description

Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value "Amit" to it.

Statement 1: x =10; Statement 2: String name = new String ("Amit");

Assignment can be of various types. Let’s discuss each in detail.

ads

Primitive Assignment:

The equal (=) sign is used for assigning a value to a variable. We can assign a primitive variable using a literal or the result of an expression.

int x = 7; // literal assignment int y = x + 2; // assignment with an expression int z = x * y; // assignment with an expression with literal

Primitive Casting

Casting lets you convert primitive values from one type to another. We need to provide casting when we are trying to assign higher precision primitive to lower precision primitive for example If we try to assign int variable (which is in the range of byte variable) to byte variable then the compiler will throw an exception called "possible loss of precision". Eclipse IDE will suggest the solution as well as shown below. To avoid such problem we should use type casting which will instruct compiler for type conversion.

byte v = (byte) a;

For cases where we try to assign smaller container variable to larger container variables we do not need of explicit casting. The compiler will take care of those type conversions. For example, we can assign byte variable or short variable to an int without any explicit casting.


Assigning Literal that is too large for a variable

When we try to assign a variable value which is too large (or out of range ) for a primitive variable then the compiler will throw exception “possible loss of precision” if we try to provide explicit cast then the compiler will accept it but narrowed down the value using two’s complement method. Let’s take an example of the byte which has 8-bit storage space and range -128 to 127. In below program we are trying to assign 129 literal value to byte primitive type which is out of range for byte so compiler converted it to -127 using two’s complement method. Refer link for two’s complement calculation (http://en.wikipedia.org/wiki/Two's_complement)

Java Code: Go to the editor

Output:


Reference variable assignment

We can assign newly created object to object reference variable as below

String s = new String(“Amit”); Employee e = New Employee();

First line will do following things,

  • Makes a reference variable named s of type String
  • Creates a new String object on the heap memory
  • Assigns the newly created String object to the reference variables

You can also assign null to an object reference variable, which simply means the variable is not referring to any object. The below statement creates space for the Employee reference variable (the bit holder for a reference value) but doesn't create an actual Employee object.

Employee a = null;

Compound Assignment Operators

Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as:

i +=8; //This is same as i = i+8;

The += is called the addition assignment operator. Other shorthand operators are shown below table

Operator NameExampleEquivalent
+=Addition assignment i+=5;i=i+5
-=Subtraction assignmentj-=10;j=j-10;
*=Multiplication assignment k*=2;k=k*2;
/=Division assignment x/=10;x=x/10;
%=Remainder assignment a%=4; a=a%4;

Below is the sample program explaining assignment operators:

Java Code: Go to the editor

Output:


Summary

  • Assigning a value to can be straight forward or casting.
  • If we assign the value which is out of range of variable type then 2’s complement is assigned.
  • Java supports shortcut/compound assignment operator.

Java Code Editor:

The latest version of this topic can be found at Assignment Operators.

Syntax

Assignment operators store a value in the object designated by the left operand. There are two kinds of assignment operations: simple assignment, in which the value of the second operand is stored in the object specified by the first operand, and compound assignment, in which an arithmetic, shift, or bitwise operation is performed prior to storing the result. All assignment operators in the following table except the = operator are compound assignment operators.

Assignment Operators

OperatorMeaning
=Store the value of the second operand in the object specified by the first operand (simple assignment).
*=Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand.
Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand.
–=Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand.
<<=Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
>>=Shift the value of the first operand right the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
&=Obtain the bitwise AND of the first and second operands; store the result in the object specified by the first operand.
Obtain the bitwise exclusive OR of the first and second operands; store the result in the object specified by the first operand.
Obtain the bitwise inclusive OR of the first and second operands; store the result in the object specified by the first operand.

Operator Keywords

Three of the compound assignment operators have text equivalents. They are:

OperatorEquivalent
&=

There are two ways to access these operator keywords in your programs: include the header file , or compile with the /Za (Disable language extensions) compiler option.

The simple assignment operator (=) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, prior to storing the value.

Objects of const and volatile types can be assigned to l-values of types that are just volatile or that are neither const nor volatile.

Assignment to objects of class type (struct, union, and class types) is performed by a function named operator=. The default behavior of this operator function is to perform a bitwise copy; however, this behavior can be modified using overloaded operators. (See Overloaded Operators for more information.)

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse is not true because there is an implicit conversion from derived class to base class but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for that takes an argument of type . Given the code

the assignment statement

can have one of the following effects:

  • Call the function operator= for , provided operator= is provided with a argument.

  • Call the explicit conversion function , if such a function exists.

  • Call a constructor , provided such a constructor exists, that takes a argument and copies the result.

The compound assignment operators, shown in the table in Assignment Operators, are specified in the form e1= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following:

  • An arithmetic type

  • A pointer, if is + or –

The e1= e2 form behaves as e1= e1e2, but e1 is evaluated only once.

Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression is not an l-value. Therefore, the legal C++ expression is illegal in C.

Expressions with Binary Operators
C++ Operators
C++ Built-in Operators, Precedence and Associativity
C Assignment Operators

expression assignment-operator expression assignment-operator : one of = *= /= %= += –= <<= >>= &= ^= |=
// expre_Assignment_Operators.cpp // compile with: /EHsc // Demonstrate assignment operators #include <iostream> using namespace std; int main() { int a = 3, b = 6, c = 10, d = 0xAAAA, e = 0x5555; a += b; // a is 9 b %= a; // b is 6 c >>= 1; // c is 5 d |= e; // Bitwise--d is 0xFFFF cout << "a = 3, b = 6, c = 10, d = 0xAAAA, e = 0x5555" << endl << "a += b yields " << a << endl << "b %= a yields " << b << endl << "c >>= 1 yields " << c << endl << "d |= e yields " << hex << d << endl; }
// expre_SimpleAssignment.cpp // compile with: /EHsc #include <iostream> using namespace std; class ABase { public: ABase() { cout << "constructing ABase\n"; } }; class ADerived : public ABase { public: ADerived() { cout << "constructing ADerived\n"; } }; int main() { ABase aBase; ADerived aDerived; aBase = aDerived; // OK aDerived = aBase; // C2679 }
UserType1 A; UserType2 B = A;
UserType1 A; UserType2 B; B = A;

0 thoughts on “Compound Assignment Operators In Ansi Code

Leave a Reply

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