2

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 } 
2
  • 9
    How about std::is_pointer? (You did tag the question C++11) Commented Sep 16, 2015 at 7:28
  • 2
    Post it as an answer @JoachimPileborg Commented Sep 16, 2015 at 8:30

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That is true but I want a differentiation parameter for variable which start with * so that I can perform different action on those variables as per my example
2

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>.

Comments

-2

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...)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.