w3resource

Understanding the use of the '-->' Symbol in C


Understanding the '-->' Operator in C: Explanation and Example


The --> is not actually an operator in C language. However, there’s a bit of a trick behind why this might appear to work in some contexts due to operator precedence and the way the compiler interprets it. Let’s dive into this with an example and explanation.

In C, --> can be misinterpreted as a sequence of two operators: the decrement operator (--) and the greater-than operator (>). When used in specific ways, it can compile because the -- and > operators are individually valid. The compiler interprets this as two separate operators, which can lead to some unexpected results but technically compiles without errors.

Code:

#include <stdio.h>

int main() {
    int x = 100;
    int y = 110;
    
    if (x-->y) {
        printf("Expression is true\n");
    } else {
        printf("Expression is false\n");
    }
    
    return 0;
}

Output:

Expression is false

Explanation:

In the code above:

  • The expression x-->y is interpreted by the compiler as (x--) > y.
  • x-- is the postfix decrement operator, which decrements a by 1 after its current value is used.
  • > is the greater-than operator, which compares the original value of x to y.

So, x-->y is equivalent to (110) > 100, which evaluates to true. After this line executes, the value of x becomes 109 due to the postfix decrement operation.

Here's an example of using --> with a while loop. As explained earlier, --> isn't a true operator but is interpreted as a combination of the decrement operator (--) and the greater-than operator (>). Let's see how this can be applied in a while loop to create a simple countdown.

Code:

#include <stdio.h>

int main() {
    int count = 5;

    // Using --> in a while loop
    while (count-->0) {
        printf("Countdown: %d\n", count);
    }

    printf("Completed!\n");

    return 0;
}

Output:

Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Countdown: 0
Completed! 

Explanation

  • The expression count-->0 is interpreted by the compiler as (count--) > 0.
  • count-- is a postfix decrement operation, which decrements count by 1 after evaluating its current value.
  • The > operator checks if the original (non-decremented) value of count is greater than 0.
  • The loop continues as long as count (before decrementing) is greater than 0. After each iteration, count is decremented by 1.


Follow us on Facebook and Twitter for latest update.