Relational Operators in C with Examples

This C Tutorial explains Relational Operators in C with Examples.

While loops, for loops often rely on test expressions that make comparisons. Such expressions are termed relational expressions, and the operators that appear in them are called relational operators in C.

Here is the complete list of relational operators in C.

  • Less than Operator (<)
  • Less than Equal To Operator (<=)
  • Equal To Operator (==)
  • Greater than Equal To Operator (>=)
  • Greater than Operator (>)
  • Not Equal To Operator (!=)

The relational operators are used to form the relational expressions used in while statements and in other C statements. These statements check to see whether the expression is true or false. Below given are three unrelated statements containing examples of relational expressions. Let’s try to understand them.

Example 1:

    while (number < 5) {
        printf("Your number is smaller than 5.\n");
        scanf("%d", &number);  /* read-in another number */
    }
 
    while (ch != '$') {        /* while ch not equals char $ */
        count++;
        scanf("%c", &ch);
    }
 
    while (scanf("%f", &num) == 1)
        sum += num;

Note in the example that the relational expressions can be used with characters, too. The machine character code (which we have been assuming is ASCII) is used for the comparison. However, we can’t use the relational operators to compare strings. For comparing strings, we have several string comparing functions defined in the string.h header file.

advertisement
advertisement

Example 2:

The relational operators can be used with floating-point numbers, too. Beware, though, We should limit to using only < and > in floating-point comparisons. The reason is that round-off errors can prevent two numbers from being equal, even though logically they should be. For example, certainly the product of 3 and 1/3 is 1.0. If we express 1/3 as a six-place decimal fraction, however, the product is .999999, which is not quite equal to 1. The fabs() function, declared in the math.h header file, can be handy for floating-point tests. This function returns the absolute value of a floating-point value—that is, the value without the algebraic sign. For example:

/* cmpflt.c -- floating-point comparisons using fabs() function */
#include <math.h>
#include <stdio.h>
 
int main(void)
{
    const double ANSWER = 3.14159;
    double response;
 
    printf("What is the value of pi?\n");
    scanf("%lf", &response);
 
    while (fabs(response - ANSWER) > 0.0001) {
        printf("Try again!\n");
        scanf("%lf", &response);
    }
    printf("Close enough!\n");
    return 0;
}

In the above program, loop continues to elicit a response until the user gets within 0.0001 of the correct value.

Note: Join free Sanfoundry classes at Telegram or Youtube

Recall that an expression in C always has a value. This is true even for relational expressions. Consider the program

/* true_false.c -- true and false values in C */
#include <stdio.h>
int main(void)
{
    int true, false;
 
    true = (10 > 5);    /* value of a true relationship  */
    false = (10 == 5);  /* value of a false relationship */
 
    printf("true = %d; false = %d \n", true, false);
    return 0;
}

When we run the above program, we found values for true is 1 and for false is 0. Are there other values in C considered to be true than just 1? Let’s experiment:

/* truth.c -- what values are true? */
#include <stdio.h>
int main(void)
{
    int n = 5;
 
    while (n)
        printf("%2d is true\n", n--);
    printf("%2d is false\n", n);
 
    n = -5;
    while (n)
        printf("%2d is true\n", n++);
    printf("%2d is false\n", n);
 
    return 0;
}

The first loop executes when n is 5, 4, 3, 2, and 1, but terminates when n is 0. Similarly, the second loop executes when n is -5, -4, -3, -2, and -1, but terminates when n is 0. More generally, all non-zero values are regarded as true, and only 0 is recognized as false.

advertisement

Alternatively, we can say that a while loop executes as long as its test condition evaluates to non-zero. This puts test conditions on a numeric basis instead of a true/false basis. Keep in mind that relational expressions evaluate to 1 if true and to 0 if false, so such expressions really are numeric.

Aha! For C, a true expression has the value 1 or any non-zero value, and a false expression has the value 0. Indeed, some C programs use the following construction for loops that are meant to run forever because 1 always is true:

    while (1) {
        ....    
        ....            /* statements */
    }

Troubles with Truth when Using of = operator for == operator

For example:

/* trouble.c -- misuse of = will cause infinite loop */
#include <stdio.h>
int main(void)
{
    long num;
    long sum = 0L;
    int status;
 
    printf("Please enter an integer to be summed ");
    printf("(q to quit): ");
    status = scanf("%ld", &num);
 
    while (status = 1) {
        sum = sum + num;
        printf("Please enter next integer (q to quit): ");
        status = scanf("%ld", &num);
    }
 
    printf("Those integers sum to %ld.\n", sum);
    return 0;
}

Above program produces output like the following:

advertisement

Please enter an integer to be summed (q to quit): 50
Please enter next integer (q to quit): 100
Please enter next integer (q to quit): 2000
Please enter next integer (q to quit): q
Please enter next integer (q to quit):
Please enter next integer (q to quit):
Please enter next integer (q to quit):
Please enter next integer (q to quit):

… and so on until you kill the program.

  1. This troublesome example made a change in the while test condition, replacing status == 1 with status = 1.
  2. The second statement is an assignment statement, so it gives status the value 1.
  3. Furthermore, the value of an assignment statement is the value of the left side, so status = 1 has the same numerical value of 1.
  4. So for all practical purposes, the while loop is the same as using while (1); that is, it is a loop that never quits.
  5. You enter q, and status is set to 0, but the loop test resets status to 1 and starts another cycle.
  6. You might wonder why, because the program keeps looping, the user doesn’t get a chance to type in any more input after entering q.
  7. When scanf() fails to read the specified form of input, it leaves the nonconforming input in place to be read the next time.
  8. When scanf() tries to read the q as an integer and fails, it leaves the q there.
  9. During the next loop cycle, scanf() attempts to read where it left off the last time—at the q.
  10. Once again, scanf() fails to read the q as an integer, so not only does this example set up an infinite loop, it also creates a loop of infinite failure, a daunting concept.

Don’t use = for ==. The assignment operator assigns a value to the left variable. The relational equality operator, however, checks to see whether the left and right sides are already equal. It doesn’t change the value of the left-hand variable, if one is present. Here’s an example:

    canoes = 5; /* *Assigns the value 5 to canoes */
    canoes == 5 /* Checks to see whether canoes has the value 5 */

Precedence of Relational Operators

The precedence of the relational operators in C is less than that of the arithmetic operators, including + and -, and greater than that of assignment operators. This means, for example, that

x > y + 2 means the same as x > (y + 2)

It also means that x = y > 2 means x = (y > 2)

In other words, x is assigned 1 if y is greater than 2 and is 0 otherwise; x is not assigned the value of y.

The relational operators have a greater precedence than the assignment operator. Therefore,

x_bigger = x > y; means x_bigger = (x > y);

The relational operators are themselves organized into two different precedence levels.

Higher precedence group

< <= > >=

Lower precedence group

== !=

Like most other operators, the relational operators associate from left to right. Therefore,

ex != wye == zee is the same as (ex != wye) == zee

First, C checks to see whether ex and wye are unequal. Then, the resulting value of 1 or 0 (true or false) is compared to the value of zee. We don’t anticipate using this sort of construction.

                Table Operator Precedence
 
Operators (From High to Low Precedence)    Associativity
               ( )                             L–R
    - + ++ –– sizeof (type) (all unary)        R–L
              * / %                            L–R
              + -                              L–R
           < > <= >=                           L–R
             == !=                             L–R
               =                               R–L

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.