The Difference Between = and ==

Last modified by Microchip on 2023/11/09 09:06

One of the biggest mistakes new C programmers make is to use = when they mean ==. It is very important to understand that these are two completely different operators.

  • "=" is used to assign a value to a variable.
  • "==" is used to compare two values for equivalence.

Be careful not to confuse = and ==. They are not interchangeable!

Example

1
2
3
4
5
6
7
8
void main(void)
{
 int x = 2;          //Initialize x
 if (x = 5)          //If x is 5,…
 {
     printf("Hi!");   //…display "Hi!"
 }
}

A very common mistake new C programmers will make is to do the following:

if (x = 5) { }

This statement will always be true because x is being assigned the value of 5 (a non-zero value) rather than being compared to 5. An assignment used where a conditional expression is expected will always be evaluated as true unless the expression equals 0. If you do fall into this trap, it can be a very hard bug to catch since the compiler won't flag it as an error. The only way you will know the bug is there is that the if block will always run, even in what should be a false condition.

In the example above, the string "Hi!" will be printed to the output window because x is non-zero. If we changed the statement to say:

if (x = 0) { printf("Hi!"); }

Then the printf() would never execute because x is always 0.