我们可以创建一个IF语句来确定变量是否已在C / C ++中声明为指针 [英] Can we create an IF statement that determines if a variable has been declared as a pointer in C/C++

查看:168
本文介绍了我们可以创建一个IF语句来确定变量是否已在C / C ++中声明为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设变量 pa 总是被声明为以下两种方式之一:

Suppose a variable pa is always declared as one of two ways:


double * pa

double * pa

OR


double pa

double pa

我们可以创建一个执行以下操作的IF语句

Can we create an IF statement that does the following


IF(pa是一个指针)
{pa [0] = 1
}

IF (pa is a pointer) { pa[0] = 1 }

ELSE
{pa = 1}

ELSE { pa = 1}

编辑:

请参阅如何确定指针数组是否有已填写C ++ / C 后续问题

推荐答案

不是直接,不是。假设有一种方法可以做到这一点,例如

Not directly, no. Suppose there were a way to do this, something like

if (__IS_POINTER(pa) {
    pa[0] = 1;
}
else {
    a = 1;
}

如果pa 不是指针会怎么样?你的程序中仍然有 pa [0] = 1; 语句,这是非法的,所以编译器会拒绝你的程序。

What happens if pa isn't a pointer? You still have that pa[0] = 1; statement in your program, and it's illegal, so the compiler is going to reject your program.

你原则上可以进行编译时测试:

You might in principle be able to do a compile-time test:

#if __pa_IS_A_POINTER
pa[0] = 1;
#else
a = 1
#endif

但是C ++预处理器的功能非常有限;它无法测试a的类型变量或表达。

but the power of the C++ preprocessor is very limited; it has no way to test the type of a variable or expression.

如果你有这个能力,你会用它做什么?告诉我们你的实际目标是什么。

If you had this capability, what would you do with it? Tell us what your actual goal is.

这篇关于我们可以创建一个IF语句来确定变量是否已在C / C ++中声明为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆