Flippowitsch
Flippowitsch

Reputation: 545

How can I pass a fixed value to a pointer?

My function needs a reference as input:

test = foo(&xyz)

Is it possible to pass a fixed value? Of course

test = foo(1.23)

does not work. I could define a new variable to pass but is this really necessary?

Thanks

Philipp

Upvotes: 2

Views: 573

Answers (2)

augurar
augurar

Reputation: 13016

Is it possible to pass a fixed value?

Not exactly, but see below.

I could define a new variable to pass but is this really necessary?

This is usually the best way to do this.

double x = 1.23;
test = foo(&x);

Let's consider what would happen if the language allowed an expression like this:

test = foo(&1.23);

This immediately creates questions: What memory location would the pointer refer to? What would be the lifespan of that memory location? What should happen if the function foo() assigns a value to that location?

Requiring a variable to point to makes the answers to these questions explicit. The pointer refers to the memory location where the variable's value is stored. The guaranteed lifespan of that memory location corresponds to the scope of the variable. If foo() assigns a value to the pointer, the value of the variable should change.


Edit: As BLUEPIXY pointed out in a comment, C99 does provide a kind of syntactic sugar for this called a compound literal, which acts as an lvalue.

test = foo(&(double){1.23});

This is semantically equivalent to the following:

double tmp = 1.23;
test = foo(&tmp);

Upvotes: 2

ad absurdum
ad absurdum

Reputation: 21317

You can't take the address of a constant, such as 1.23 in C. But, you can use a compound literal to create an unnamed object, and take its address as suggested by @BLUEPIXY:

test = foo(&(double){ 1.23 });

It is unclear why you might want to do this, though, since usually when a pointer is passed into a function, the idea is that the object will be modified and used again after modification. Without an identifier, there would be no way to access the object created by the compound literal after foo() has returned.

Upvotes: 3

Related Questions