Reputation: 13789
Is there any way to get address of literals?
For example:
floar r = 1.0;
float area = r * r * 3.14;
float* addressOfPI = ? // TODO: Address of 3.14 in previous line
Upvotes: 0
Views: 158
Reputation: 154602
In C, taking the address of a floating constant (OP's "literal") or integer constant is not available. It is an "rvalue" or "value of an expression" and lacks an address.
Yet taking the address of a compound literal (C99) is OK.
// Add more types as needed
#define constant_address(X) _Generic((X), \
double : &((double){X}), \
float : &((float){X}), \
unsigned: &((unsigned){X}), \
int : &((int){X}), \
default: 0 \
)
int main(void) {
#define MY_PI 3.1415926535897932384626433832795
double *addr_pi = constant_address(MY_PI);
printf("%f %p\n", *constant_address(MY_PI), (void *)constant_address(MY_PI));
printf("%f %p\n", *addr_pi, (void *)addr_pi);
printf("%8d %p\n", *constant_address(1234), (void *)constant_address(1234));
return 0;
}
Output
3.141593 0x28cbb0
3.141593 0x28cba8
1234 0x28cbc0
To be clear: In C parlance, code can take the address of a literal. Yet 3.14
is not a literal. It is a floating constant.
Upvotes: 1
Reputation: 122503
Literals like 3.14
are rvalues, they don't have an address. This is the difference between lvalue and rvalue.
Upvotes: 2