是否可以将指针传递给文字?

Is it possible to pass a pointer to a literal?

假设我们有:

void foo(int *num){}

而且我们知道我们总是将 5 作为参数传递,然后可以这样做:

int var = 5;
foo(&var);

有什么语法可以避免显式变量声明吗?

本质上是这样的:

foo(&(5));

您只能获取 lvalue 的地址。文字是纯右值,而不是左值,因此您不能获取文字的地址。从概念上讲,像 5 这样的文字不需要任何存储,没有某种形式的存储就没有地址。

不过,您可以将其传递给 const int &

void foo(const int &) {}

int main()
{
    foo(5);
}