Search code examples
ccallback

Passing a function with args as a callback in C?


I have the following simplified code and I would like to know if it is possible to pass an argument to the callback function below:

#include <stdbool.h>
#include <string.h>
#include <stdio.h>

char* foo = "hello!!!!";

bool is_not_char(char x)
{
    bool result = false;
    if (x == '!') result = true;
    
    return !result;
}

void sv_chop_left_while(char* input, size_t count, bool (*predicate)(char x))
{
    size_t i = 0;
    while (i < count && predicate(input[i])) {
        printf(">%c< [%d]\n", input[i], i);
        i += 1;
    }
}

int main(void) {
  sv_chop_left_while(foo, strlen(foo), is_not_char);
}

So is it possible to do something like:

sv_chop_left_while(foo, strlen(foo), is_not_char, '!');

Right now, that char used for the comparison is hardcoded. I'm aware that this is possible by completely avoiding the cb mechanics, but this is a POC for these kind of issues.

The output looks like that right now:

>h< [0]
>e< [1]
>l< [2]
>l< [3]
>o< [4]

Some references:

The original projects repo - https://github.com/tsoding/sv/tree/master

My CompilerExplorer link - https://godbolt.org/z/9G8e9sb5M


Solution

  • You could do:

    #include <stdbool.h>
    #include <string.h>
    #include <stdio.h>
    
    char* foo = "hello!!!!";
    
    typedef bool (*predicate_t)(char x, char y);
    
    bool is_not_char(char x, char y)
    {
        bool result = false;
        if (x == y) result = true;
        
        return !result;
    }
    
    void sv_chop_left_while(char* input, size_t count, predicate_t predicate, char y)
    {
        size_t i = 0;
        while (i < count && predicate(input[i], y)) {
            printf(">%c< [%d]\n", input[i], i);
            i += 1;
        }
    }
    
    int main(void) {
      sv_chop_left_while(foo, strlen(foo), is_not_char, '!');
    }