user3542577
user3542577

Reputation: 35

What does " = " instead of " == " mean in c if statement?

#include <stdio.h>
int main(){
   int b = 10,a;
      if (a = 5){
         printf("%d",b);
      }
   }

In the above program if statement always returns true even if i change the data type of the variable "a" from "int" to "char".

What does = mean in the if statement??

Upvotes: 0

Views: 2200

Answers (5)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

Please note that in C it is allowed in a boolean expression to use the assignment operator. Because of that = as assignment must be a different symbol than = for comparisson.

Because in a language such as BASIC there can be no confusion of whether the programmer means assignment or comparisson, BASIC uses the same symbol for the two meanings:

C:

if ((a=5)==5) ...        // a is set to 5 and then compared to 5

Basic:

a = 5                    ' assignment
If (a = 5) Then          ' comparison

Upvotes: 0

A single = means an assignment operator, that means you are changing the value of a and using this value in the if statement.

if(a = 5) {
// some code
}

is the same of:

a = 5;
if(a) {
// some code
}

The == means a operation of logical equivalence, witch will return 1 if the two values are the same or 0 if they aren't the same.

Upvotes: 2

Freek Wiekmeijer
Freek Wiekmeijer

Reputation: 4940

The single = will assign the value 5 to a. Assignment will evaluate true if the assignment value evaluates true (i.e. not 0, null etc). If it evaluates true, the function will branch into the if statement block. And there's the side effect that a gets value 5.

Upvotes: 1

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12393

= is an assignment operator in C. According to C99 6.5.16:

An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

It means that expression a = 5 will return 5 and therefore instructions inside if block will be executed. In contrary, if you replaced it with a = 0 then 0 would be returned by assignment expression and instructions inside if would not be executed.

Upvotes: 3

Abdullah Nehir
Abdullah Nehir

Reputation: 1047

  • Assignment operator returns the assigned value back.
  • "if" statement decides to true if checked value is other than zero

So:

  • "if (a=0)" returns false
  • "if (a=x) where x!= 0" returns true

Thus you should use "==" operator in the if statement as other friends told.

Upvotes: 1

Related Questions