C - double equal sign == vs single equal sign =

Introduction

The most common comparison is the double equal sign.

The == operator isn't the same as the = operator.

The = operator is the assignment operator, which sets values.

The == operator is the comparison operator, which checks to see whether two values are equal.

The following code makes an evaluation on whether both variables are equal to each other.

Demo

#include <stdio.h> 

#define SECRET 17 /*from  w  ww .  j a  v a  2  s.com*/

int main() 
{ 
   int guess; 

   printf("Can you guess the secret number: "); 
   scanf("%d",&guess); 
   if(guess==SECRET) 
   { 
       puts("You guessed it!"); 
       return(0); 
   } 
   if(guess!=SECRET) 
   { 
       puts("Wrong!"); 
       return(1); 
   } 
}

Result

difference between = and ==

One of the most common mistakes made by every C language programmer is using a single equal sign instead of a double in an if comparison.

Demo

#include <stdio.h> 

int main() /*w  w  w  .j  a va2 s  .co m*/
{ 
     int a; 

     a = 5; 

     if(a=-3) 
     { 
         printf("%d equals %d\n",a,-3); 
     } 
     return(0); 
}

Result

The result of a variable assignment in C is always true for any non-zero value.

Related Topic