ostrichofevil
ostrichofevil

Reputation: 734

Create pointer to value in one line

I would like to create a pointer to a value in one line; I want the same functionality as this:

int i = MY_VALUE
int * j = &i;

However, I want to do this in one line, and do not want to use two variables. I know that I can do this:

int * i = new int (MY_VALUE);

But I don't want to use dynamic memory; I want to use static memory.

Is there a way that I can allocate a pointer to a value, statically, with one variable, in one line?

Upvotes: 3

Views: 4010

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

No, you cannot have a pointer to a value, you can only have a pointer to a variable or pointer to an object (lvalue).

To elaborate, from C prespective, quoting C11 chapter §6.5.3.2 for the usage of & operator

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

So, something along the line of

int * p = &10;

is purely invalid.

Upvotes: 2

Richard Hodges
Richard Hodges

Reputation: 69882

If you must...

int i = 5, *p = &i;

Upvotes: 4

Related Questions