-3

There's two C Language flies.
main.c:

// main.c
#include <stdio.h>

extern int * a;
extern int d;

int main(){
    printf("==> a==>%p\n", a);
    printf("==>&a==>%p\n", &a);
    printf("==>%zd\n", *a);
    printf("======================\n");

    int c = 5;
    a = &c;

    printf("==> a==>%p\n", a);
    printf("==>&a==>%p\n", &a);
    printf("==>%zd\n", *a);
    printf("======================\n");

    d = 5;
    printf("==>%d\n", d);

    return 0;
}

global.c:

// global.c
int b = 1;
int * const a = &b;
int const d = 1;

I run the command cc main.c global.c and ./a.out,Then I find the variable a's value can be changed, and the variable d's value can't be changed.
Why?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
ErYe
  • 53
  • 5
  • You defined `d` as constant in global.c , it's only visible to main.c, you cannot alter the value. – R__raki__ Mar 28 '16 at 09:39
  • @ErYe Can you elaborate a bit on "Can't be changed"? Are you getting a compiler error (unlikely, as you are tricking the compiler into thinking `d` would be writable)? A linker error (maybe, if you are using a C++ compiler) or a core dump (more likely, as const allows the linker to put the variable into a non-writable segment) – tofro Mar 28 '16 at 10:53
  • "*Then I find the variable a's value can be changed*" how? And also what does the program print out? – alk Mar 28 '16 at 13:11
  • OT: `zd` is for `ssize_t`, you pass an `int`. – alk Mar 28 '16 at 13:16

1 Answers1

1

By using :

int const a=10;

the value of a remains constant throughout the execution of program.

Using:

int* const a=&b;

The value contained by a i.e. the address of b remains constant throughout.

The value of b can change.

Sarthak Agarwal
  • 128
  • 1
  • 2
  • 16
  • My code is `int * const a = &b;`, but not `const int* a=&b;` And in the `mian.c` file, the `a`'s value can be changed. – ErYe Mar 28 '16 at 09:14
  • In the `main.c` file, why I can change `a = &c;`? – ErYe Mar 28 '16 at 09:21
  • 1
    I think his point is that if `d` is defined in two compilation units, one declaring it as `extern int` and the other as `const int`, the compiler has no way of knowing these differences across compilation units. I am curious too. – Paul Ogilvie Mar 28 '16 at 09:24
  • My gcc 4.9 compiled version of the code shown crashes in both cases: `a= ...` as well as `d=...`. – alk Mar 28 '16 at 13:14