views:

66

answers:

2
#include <stdio.h>

enum bool
{
  true, false
};

typedef bool
(*compare_fun) (int, int);

I get an error when I enter the above code. How do I make a function pointer that needs to return a boolean?

+2  A: 

it should be typedef enum bool (*compare_fun)(int, int); :)

Also make sure your implementation doesn't have predefined bool true and false

Note that in C++ when you define an enum, class or struct, say with name A, then you can declare a variable of type A like

A var;

or

class A var; //or struct A var; or enum A var;

in C, only the second syntax is valid. That's why they usually make a typedef. like this

typedef enum {true, false} bool;

in this case you can use your original syntax :

typedef bool (*p) (int, int);

HTH.

Armen Tsirunyan
+1  A: 

What about:

typedef enum 
{
    true, false
} bool;

bool
(*compare_fun) (int, int);
sje397
Why typedef the enum? it has a type already.
Blank Xavier
@Blank Xavier: By that reasoning, you'd never use `typedef` anywhere. `typedef` always creates an alias to an *existing* type.
jamesdlin
True; there is more to it than that. The problem is that even when typedefed, *you still need to know the underlying type to use it*. So typedefing acts and acts only to make reading the code harder, since you have to look up and then remember the real type while you're reading.
Blank Xavier
@Blank Xavier - I don't get your point. I can use the 'bool' type easily, and return 'true' or 'false' without additional keywords or anything tricky. To use an 'int' you have to have some understanding of what values an 'int' can have. If the type you create with 'typedef' is sensible and intuitive, it makes sense.
sje397
Everyone knows the types which are a part of C. Those are part of what your brain learns to read when it learns C. But every additional type is not generic - even enum bool - and so every new type is an incremental burden on the reader, requiring an increment of attention and memory, which subtracts from that which is available to comprehend the code.
Blank Xavier
The only way to get round this is to operate on the typedef *only* with function calls, such that the user literally does not need to know the underlying type. If the underlying type must be remembered (which is not the case for int, since it is what it is and it is part of C, rather than part of an individuals code) then it is a burden.
Blank Xavier
That would just mean the user has to remember (or look up) the function calls instead. If 'enum bool' is an additional type, then so is 'struct x'. I think we're fairly used to additional types and the minor burden that places on our memory (especially when working within a particular code base for a period of time). I'd rather that than the fairly useless extra typing.
sje397