Getting the address of package scope const variable

Below is my ‘C’ code and ‘golang’ code :slight_smile:

C code

$ cat 5.c
#include <stdio.h>

const int a = 10;

int main(void) {
   printf("Address of a is %x\n", &a);
   return 0;
}
sudhe.s@5636nrd-ssampath /cygdrive/c/Software/Install/cygwin/home/sudhe.s/gocode/src
$ gcc -o 5 5.c

$ ./5
Address of a is 403030

Golang code:

$ cat 5.go
package main

import "fmt"

const a int = 10

func main() {
   fmt.Println("Address of a ", &a)
}

$ go build 5.go
# command-line-arguments
.\5.go:8: cannot take the address of a

sudhe.s@5636nrd-ssampath /cygdrive/c/Software/Install/cygwin/home/sudhe.s/gocode/src

Question is : Why is ‘golang’ giving the error ‘Cannot take the address of a’ ? I a new to golang and appreciate any input to the above.

Thanks,

In Go, constants are not addressable. I guess this helps the compiler optimizing the code.

1 Like

This is sadly not possible. Const is not the same as C’s const.

Maybe there is another way to solve your problem. If you could take the address of a constant, what would you do?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.