Rust equivalent to this C expression

I've come across what I think is C code with the following expression for decrementing a variable based on another variable:

x -= y > z;

Am I correct that the equivalent is

x = { if y > z { x - y } else { x };

No, in C bools automatically get converted to ints. In this case the equivalent rust is x -= if y > z { 1 } else { 0 } or shorter x -= (y > z) as u32.

3 Likes

You can also explicitly convert bool into integer types:

x -= (y > z) as i32;
1 Like

I would typically write this as

if y > z { x -= 1 }
9 Likes

Exactly.

I wish programmers would not try to show how smart they are by sprinkling stupid tricks like this all over their code. In whatever language.

There is no point. You are not helping performance. Mostly optimizers can do better at that than you.

It only obfuscate ones intentions. By mixing up bool and int in this case. And causes the reader to have to stop and think about it unnecessarily. As in this question here.

Grrr...

4 Likes

Yeah implicitly converting boolean values to integer values seems unnecessarily confusing.

On thinking about it a bit. Code phrases like x -= y > z; are probably very common in C. Any long time C programmer would be chuckling that anyone would have to pause for a millisecond on reading it to know what it does. It is "idiomatic C". C has many such idioms.

Which starts me understanding why I have always felt nervous twinges when I read people here talking about "Idiomatic Rust".

The thing about idioms is that they are immediately obvious to native speakers of the language. But that can be total gibberish to non-natives that are trying to learn the language or at least trying to understand something for whatever reason.

We live in a world of many languages. Both human and programming languages. Forget any dogmatic idea of "idiomatic". If you want to make yourself understood by the widest audience, no matter what their programming language experience, write "obvious Rust". Or obvious whatever language you have chosen.

A recent example of this kind of mandatory idiomatic thinking happened here: Rust performance help (convolution). A ton of contorted "idiomatic Rust" solutions that were very obscure and performed badly. Happily ending with a short and sweet, dead obvious, solution that performed well to boot.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.