Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function as condition in for loop – does anyone write like this in C?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading