Is it possible to pass an operator as an argument in C?

closed account (42AMoG1T)
I'm writing a program in C that performs operations on an array of 4-byte unsigned integers. Here's some usage examples to give you an idea:

1
2
3
+ n m    // print sum of elements at indexes n and m
& n m    // bitwise and of elements...
< n m    // shift element at index n by m bits 


I will have to implement functions for sum, bitwise-and, bitwise-or, xor, left-shift, right-shift... All with the same function format:

1
2
3
void print_operation(unsigned n, unsigned m) {
    printf("%u\n", n some_operator m);
}


Is there any way that I can pass an operator as an argument so that I can have a single elegant function that looks like this? I'd really like this to work like callback functions.

1
2
3
void print_operation(unsigned n, unsigned m, some_type oper) {
    printf("%u\n", oper(n, m));
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>

unsigned int plus( unsigned int a, unsigned int b ) { return a + b ; }
unsigned int bit_and( unsigned int a, unsigned int b ) { return a & b ; }
unsigned int bit_shift_left( unsigned int a, unsigned int b ) { return a << b ; }

const char operators[] = { '+', '&', '<' } ;
enum { N = sizeof(operators) };
const char* const operator_names[] = { "plus", "bit-and", "bit-shift-left" } ;

typedef unsigned int operation( unsigned int, unsigned int ) ;
operation* operations[] = { plus, bit_and, bit_shift_left } ;

int pos( char operator )
{
    for( int p = 0 ; p < N ; ++p ) if( operators[p] == operator ) return p ;
    return -1 ;
}

const char* name( char operator ) { int p = pos(operator) ; return p != -1 ? operator_names[p] : "" ; }
operation* function( char operator ) { int p = pos(operator) ; return p != -1 ? operations[p] : NULL ; }

void print_operation( unsigned int n, unsigned int m, char oper )
{
    operation*  fn = function(oper) ;
    if( fn != NULL ) printf( "%s: %u %c %u == %u\n", name(oper), n, oper, m, fn(n,m) ) ;
    else printf( "unsupported operation '%c'\n", oper ) ;
}

int main()
{
    print_operation( 22, 87, '+' ) ;
    print_operation( 16, 3, '<' ) ;
    print_operation( 25, 19, '&' ) ;
    print_operation( 1, 2, '?' ) ;
 }

http://coliru.stacked-crooked.com/a/a1e0a894266165eb
Topic archived. No new replies allowed.