When would I use = vs == in programming?

Answering a programming beginner.

Answer by Sharmilli Priyadarsini:

= is an assignment operator, we use a "equal to" symbol whenever we want to assign right hand side RHS value to the left hand side LHS.
E.g:

int a = 1;

// the value 1 is assigned to the variable "a", whenever you use "a" it automatically takes the value of "a" as 1 as long as it is not modified to some other value within the scope of the variable.

== is a logical operator, that you usually use while checking the left
hand side LHS is exactly equal to right hand side RHS. The other logical operators are < Less than ,> greater than,<= less than or equal to ,>= greater than or equal to ,!= not equal to. The output of logical operator is always true or false. You will be using this operator in condition statements like if and ternary operators uses both = and ==.
E.g:

int a=1;
int b= 2;
int c= 1;

//Conditional operator returning true or false uses ==

if(a==c){

//true since value of a and c are equal ie 1.

a=b;// assignment operator uses =, now value of b is assigned to a, so value of "a" is equal to 2.

}

//ternary operators also uses == to check for true or false, followed by assigning the  values to LHS from true section if condition in == satisfies, otherwise assign the false section to LHS.

// now a,b are equal with the value 2 and value of c is 1

c= a==c?c:b;

// The above is a ternary statement, first it checks if value of a is equal to c, if it is equal then c remains same, otherwise b overwrites the value of c.

//  Now a,b,c are all equal with the value 2

When would I use = vs == in programming?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s