1

I want to compare a value, pass with void*,who can be char/short/long type with a constant long type. But this code didn't work. I don't understand.

void compar (void* p_value) {
    if (*p_value > CONST_MAX) {
        *p_value = CONST_MAX;

     } else if( *p_value<CONST_MIN ) {
         *p_value = CONST_MIN;
     }
}

thx.

Badda
  • 1,329
  • 2
  • 15
  • 40
Peretti
  • 17
  • 6
  • 2
    You'll need to cast it first -- what is the type / meaning of `CONST_MAX`? – cat May 29 '17 at 12:29
  • How many bytes should the compiler write? – stark May 29 '17 at 12:30
  • 1
    A value pointed to by `void*` doesn't have any specific type. How would the compiler know how to treat the value when you dereference the pointer? – Some programmer dude May 29 '17 at 12:30
  • You forgot an ending brace to close the else condition. Thought it could fix your problem since you didn't tell what your error were. Better as a comment though. – Badda May 29 '17 at 12:32
  • What are you _actually_ trying to achieve? Read this: [The XY Problem](http://xyproblem.info/) – Jabberwocky May 29 '17 at 12:32

4 Answers4

4

It would be better to change your function signature to:

#define TYPE_INT 1
#define TYPE_LONG 2

void compar (void* p_value, int type){

then basd on the type, cast the "thing" passed (or the thing pointed to) to the type and compare.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
3

You can't know the type of a variable in C language without a gcc extension or the C11 standard (further info at this link). By the way, this kind of problem is often solved passing another argument with the type of the variable.

simo-r
  • 733
  • 1
  • 9
  • 13
1

A void* is a pointer to anything. The comparison operators need to know what you're comparing before it can be compiled into something meaningful for the processor to process.

There are several approaches that could solve it for you.
1) Use macros (so it compares it inline - no void*)
2) Pass the type in to the comparison fn
3) Write different functions for each comparison type
4) Cast everything to an (int) before passing it to your function and forget about void pointers altogether. This is not what they're for.

noelicus
  • 14,468
  • 3
  • 92
  • 111
0

If that code block is part of a bigger code where you called that method to compare then it should not be a problem because when you call that code block it should also pass the type of data p_value should be. But as it is, p_value has is ???? and so it will not compile properly.

nuji
  • 11
  • 8