What is the "-->" operator in C?

Asked

Viewed 58 times

4

I’ve never seen this operator before, just another like ->, but it makes no sense in the context of that code.

Code

#include <stdio.h>


int main() {
    int x = 10;
    while (x --> 0) { // x goes to 0
        printf("%d ", x);
    }
}

Exit

9 8 7 6 5 4 3 2 1 0

1 answer

7


Actually, what’s going on is x-- greater than 0, i.e., the while is decreasing x while x greater than 0:

#include <stdio.h>

int main() {
    int x = 10;

    while (x-- > 0) { // x goes to 0
        printf("%d ", x);
    }

    printf("\nX = %d", x);

    return 0;
}

See online:https://repl.it/@Dadinel/Stainedfunnyprocedures#main. c

Notice that at the end of the while, x will be -1.

  • I saw the "// x Goes to 0" and decided to share something else. All the Eng. Computer Science teachers I’ve had suggested the golden rule: ALWAYS avoid using go-to commands on high-level Lps (not to say never use). I do not know if the excerpt of this post was found on the web. It’s good to remember this rule because, although certain high-level Lps contain go-to, this command can generate issues, and at least hinder the readability of the source. As a beginner programmer, trust me, there will come times when apparently a go-to would solve everything, but resist and do otherwise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.