Home > OS >  Function as condition in for loop - does anyone write like this in C?
Function as condition in for loop - does anyone write like this in C?

Time:02-21

I'm re-discovering C after years of using high level languages like C#, Java and I'm messing around with generic-like functions, I'm trying to write something like functors etc.

I wrote something like this:

#include <stdio.h>

static int test(int x){
    return (x < 5) ? 1 : 0;
}

int main()
{
    for (int i = 0; test(i); i  ){
        printf("i = %d\n", i);
    }
    return 0;
}

So it works. The question is: does anyone write like this in C?

Opinion-based free version: does writing like this happen among professional C programmers (operating systems, databases, standard libraries source code)?

Is this considered as bad practise, not popular, or not very useful for some reasons?

Example above is silly, but actually I'm messing around with object-oriented programming in C and I would like to use something like this in a generic-like function and pass test(some_struct_t) function as argument.

CodePudding user response:

Of course functions are used in while loop conditions (no matter if while or for is used).

WidgetIterator wi = ...;
Widget w;
while ( WidgetIterator_next(wi, &w) ) {
   process_widget(w);
}

Not for something silly like the example you gave, though. (x < 5) ? 1 : 0 is a weird way of writing x < 5, and using a function for just x < 5 simply obscures things. That's not good. It's antithetical to good programming practices.

  • Related