简体   繁体   中英

How can I get address of literals?

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

Literals like 3.14 are rvalues, they don't have an address. This is the difference between lvalue and rvalue.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM