Sorry if it's a stupid question, but I couldn't find much information. I just want to assign the result of a comparison in a variable, like this:
int a = 3, b = 2; // In actual code they're not integer literals
int result = a > b;
When compiling, gcc
(with -Wall
) doesn't complain, and looking at the assembly output I found it's translated to cmp
and setle
(or setg
etc.). I'm wondering whether it's invalid (C) code or considered bad practice, since I see it's never used.
This is a perfectly valid C code. The behavior is detailed in section 6.5.8.6 of the C99 standard:
Each of the operators
<
(less than),>
(greater than),<=
(less than or equal to), and>=
(greater than or equal to) shall yield1
if the specified relation is true and0
if it is false. The result has typeint
.
Unless you are maintaining legacy code that must be compatible with pre-C99 compilers, consider using <stdbool.h>
and bool
type instead of an int
.