ManishB
ManishB

Reputation: 171

Macro to decide whether variable is pointer or not

I want a macro which can decide whether the given variable is pointer or not?

My requirement is as below:

#define IS_PTR(x)       ?
#define MY_TEST(x)      IS_PTR(x)?&(*x):x  ===> 1 if ptr and 0 means ref.

void main()
{  int a;
   int *b;
   int *c = MY_TEST(*b)   ====> I have to *b instead of b directly 
                          ====> after precompilation int *c = &b  
   int d = MY_TEST(a)     ====> after precompilation int d = d   
}

Upvotes: 2

Views: 133

Answers (3)

Garogolun
Garogolun

Reputation: 353

In C11 you can use generic selection. I don't really understand what you want to do however.

#include <stdio.h>
#define IS_PTR(x) _Generic((x), int *: 1, int: 0)

void main() {
    int a;
    int *b;

    printf("IS_PTR(a) = %d\n", IS_PTR(a));
    printf("IS_PTR(b) = %d\n", IS_PTR(b));
}

This outputs

IS_PTR(a) = 0
IS_PTR(b) = 1

on my system.

Edit: For some reason people are downvoting this answer. Although this doesn't work for distinguishing pointers from non-pointers in general, it does work for an arbitrary number of types. It could be good enough for the OP or someone else who stumbles across this question.

The currently topmost answer claims that pointers are just integers "under the hood". Depending on what exactly is meant with "under the hood", that is not entirely correct. (In the end, everything is just integers and floats...)

Upvotes: -2

Davislor
Davislor

Reputation: 15134

In C++, you can declare this as a template that returns false, then specialize that template for class T so that is_ptr(const T* _) returns true.

C++11 has is_pointer in <type_traits>.

Upvotes: 2

rainhaven
rainhaven

Reputation: 138

Under the hood, a pointer is same as a 32-bit or 64-bit unsigned integer. I don't think there is a way to differentiate a pointer from a primitive type in C.

Upvotes: 2

Related Questions