[英]Macro to decide whether variable is pointer or not
我想要一個可以確定給定變量是否為指針的宏?
我的要求如下:
#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
}
在幕后,指針與32位或64位無符號整數相同。 我認為沒有辦法將指針與C中的原始類型區分開。
在C ++中,可以將其聲明為返回false的模板,然后將其專門用於class T
以便is_ptr(const T* _)
返回true。
C ++ 11在<type_traits>
具有is_pointer
。
在C11中,您可以使用通用選擇。 我真的不明白你想做什么。
#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));
}
這個輸出
IS_PTR(a) = 0
IS_PTR(b) = 1
在我的系統上。
編輯:由於某些原因,人們不贊成這個答案。 盡管這通常無法將指針與非指針區分開,但它確實適用於任意數量的類型。 對於OP或偶然發現此問題的其他人來說可能已經足夠了。
當前最高的答案聲稱指針只是“幕后”的整數。 取決於“幕后”的確切含義,這並不完全正確。 (最后,一切都只是整數和浮點數...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.