Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operators

Tags:

c++

The following expression is valid in C++:

A = B = C = 10;

The variables A, B, and C will now contain the value 10.

I'm trying to figure out how to make it so A, B, and C can contain the value of 10 when declared, not assign them later;

#include <iostream>
using namespace std;

int main()
{
   int A, B, C, = 10;
   int result;
   result = A = B = C = 10;
   cout << A << B << C << 10;

   result 0;
}
like image 701
Geraldine Jones Avatar asked Oct 24 '19 18:10

Geraldine Jones


People also ask

Which are assignment operators?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.

What are assignment operators with example?

The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A.

What is assignment operator and its types?

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. compound assignment, in which an arithmetic, shift, or bitwise operation is performed before storing the result.


2 Answers

In C++ every variable definition has to have its own initializer. If you want to chain that then you need to use something like

int A = 10, B = A, C = B;

This will do what you want but it is required to you manually specify the initializer.

like image 170
NathanOliver Avatar answered Oct 31 '22 13:10

NathanOliver


You cannot do what you want directly. However, in my opinion wanting to initialize them with the same value is reason enough to define a class:

struct ABC {
    int A,B,C;
    ABC(int x) : A(x),B(x),C(x) {}
};

If there is a relation between A,B and C, make it explicit. Now you can use a single value to initialize them:

ABC abc{10};
like image 26
463035818_is_not_a_number Avatar answered Oct 31 '22 15:10

463035818_is_not_a_number