r/C_Programming • u/OBSIDIAN_W • Jun 07 '26
Ternary tests
Hello everyone.
What do you think about ternary tests?
Within a small codebase, of course.
#include <stdio.h>
unsigned int mysize(char *line)
{
// NULL check.
if (line == NULL) return 0;
// unsigned is used because a string cannot have a negative length.
unsigned int count = 0; // counter
while (line[count] != '\0') count++; // count to the end of the line
return count;
}
void run_test(char* input, unsigned int excepted)
{
unsigned int size = mysize(input); // We call the function to count characters in a string and write it to a variable.
// Test.
size == excepted ? printf("\033[32mSuccess test: %s | %d\033[0m\n", input, size)
: printf("\033[31mFailed test: %s | %d\033[0m\n", input, size);
}
int main(void)
{
run_test("world", 5);
run_test("Hello world", 11);
run_test("bingo", 5 );
run_test("430043414154-u9cr74u9rslkr47i30i23cafce9m4ace.apps.googleusercontent.com", 72);
run_test("~/Desktop/localcode/python/autoUS", 33);
run_test("installed", 9 );
run_test("Downloading pycparser-3.0-py3-none-any.whl (48 kB)", 50);
run_test("Владивостокский городской округ", 31);
run_test("", 0 );
run_test("I'm designing a fiber library in C (for learning purp", 53);
run_test("google-auth-oauthlib,", 21);
run_test("pipe", 4 );
run_test("5235554231739324534", 19);
run_test("https://accounts.google.com/o/oauth2/auth", 41);
return 0;
}
8
Upvotes
7
u/chrism239 Jun 07 '26
Appreciating it's just an example, but no love for
strlen()?21
u/questron64 Jun 07 '26
That is just completely unnecessary. Use an if statement. Since this will be done so, so many times, you'll probably want to wrap it in a function or macro. Even small projects can have hundreds of tests, and copying and pasting that if statement so many times will be a maintenance nightmare.
19
u/No-Dentist-1645 Jun 07 '26
I don't mind ternary expressions for writing data to a variable, but using them for control flow like you are doing with
printfjust seems ugly and bad practice, I would 100% avoid that and use an if.5
u/tangerinelion Jun 07 '26
No, dislike. If you wanted to do this, though...
3
u/flyingron Jun 07 '26
If you don't use the result of the expression, I'd prefer if/else.
4
u/RainbowCrane Jun 07 '26
That line with the ternary operator and printf is needlessly confusing, you gain no benefit from mashing all of that logic into one line. It only serves to make your code less readable.
Something like this makes more sense.
static const char* success_format = "\033[32mSuccess test: %s | %d\033[0m\n"; static const char* failure_format = "\033[31mFailed test: %s | %d\033[0m\n";
const char *format = (size == expected ? success_format : failure_format);
printf(format, input, size);
3
u/tharold Jun 07 '26
I'd put the ternary test in the argument to printf
1
u/Brisngr368 Jun 09 '26
I think making the test return a string would be clearer instead of two printf calls