It was weird when I first saw it: A conditional expression used to determine a value. It sounds odd, but it works.
Consider m<3. This expression isn’t an assignment; it’s a condition. Normally, you see it in a conditional statement, such as:
if( m<3 )
The conditional expression evaluates as either TRUE or FALSE, though numeric values are behind each logical term: In C programming, FALSE is zero. TRUE is any other value. (In other programming languages, you may find -1 is always FALSE, though this value is TRUE in C.)
What’s happening internally is that the compiler does the math on the conditional expression. Effectively, m<3 is equal to zero when variable m is three or greater; it’s one when m is less than three. This operation occurs for every conditional expression. You can see it happen by running the following code:
2022_05_07-Lesson.c
#include <stdio.h>
int main()
{
int m = 1;
printf("%d\n",m<3);
m = 5;
printf("%d\n",m<3);
return(0);
}
From the printf() statement at Line 6, I might think, “What the heck is going to print?” Because variable m is one, the result of m<3 is TRUE. The decimal integer value (%d) output is 1.
In the Line 8, the conditional expression becomes FALSE. The value output is zero. Here’s the sample run:
1
0
Using a conditional expression as a value rather than using the results to make a decision is unusual, but it happens. I remember the first time I saw such a construction in a program. I scrutinized the code because I was unsure why the condition’s result was used in such an unexpected manner. In this instance, the statement looked like this:
r = offset + m<3;
I forget the specifics of what the code did, as the unusual construction caught my attention. Regardless of what variable r is trying to represent, the result is either equal to offset when variable m is three or greater or equal to offset plus one. It's an interesting construction, one that works, but was completely new to me.