Jun 8, 2014

C Programming #08: Operators - Relational

There are quite a few relational operators in C, which helps in decision making in C. In general relational operator finds relation between two variables/constants. They don't work on strings. Result of Relational operator is true or false, which is represented by a number. In C value zero means it is false and all non-zero numbers are true.


Equal

'==' is the equal operator. (Non intuitive, in maths = is equal operator, in C = is for assignment which will be covered later). Following program will depict typical use and outcome of Equal operator


#include <stdio.h>
int main() 
{
   int a = 10;
   float b = 2.1;
   float c = 2.1f;

   printf("Is a equal to 10 %d\n", a == 10);
   printf("Is a equal to 15 %d\n", a == 15);
   printf("Is a equal to b  %d\n", a == b);
   printf("Is b equal to 2.1 double %d\n", b == 2.1);
   printf("Is c equal to 2.1 float %d\n", c == 2.1f);

   return 0;
}

output of above program is


Is a equal to 10 1
Is a equal to 15 0
Is a equal to b  0
Is b equal to 2.1 double 0
Is c equal to 2.1 float 1

In above outcome things around integer can be easily grasped. But what has happened in floating ? Allow me to explain it in detail. In below expression
float b = 2.1;
b is float but 2.1 is double in above initialization. 2.1 double has its IEEE representation which has different precision and internal representation when compared to float.
Hence the b == 2.1 will try to compare b (float) with double 2.1 which would be different in internal representation.

Not Equal

'!=' is the not equal operator. (Almost intuitive, in maths we strike equal to get not equal sign). Following program will depict typical use not equal operator


#include <stdio.h>

int main() 
{
   int var = 'a';

   printf("Is var not equal to 'z' %d\n", var != 'z');
   printf("Is var not equal to 'a' %d\n", var != 'a');

   return 0;
}
output of above program is


Is var not equal to 'z' 1
Is var not equal to 'a' 0

Again you have to be careful with float and double as you were with Equal operator.

Others

Other relational operators are


Greater than
>
Lesser than
<
Greater than or Equal to 
>=
Lesser than or Equal to
<=


No special attention is needed here. Make sure you maintain same carefulness with float and double here also.

Links

Quiz - Not Yet written !!
Next Article -  C Programming #09: Operators - Logical
Previous Article - C Programming #07: Operators - Arithmetic
All Article - C Programming

No comments :

Post a Comment