0

Why in this code compiler does not show error Use of unassigned local variable when taking the address of that variable?

int i;
int* p = &i; // Use of unassigned local variable i ?
int j = *p; // j = 0
j = i;      // both valid

This will compile fine and the value of j will be 0.

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • 1
    Because there may be some codes like `*p = 5;` compiler can not easily detect it is setting 5 to `i`. – Eser Sep 04 '15 at 21:08
  • @Eser there is no need for that. compiler could stop at `&i` Use of unassigned local variable. – M.kazem Akhgary Sep 04 '15 at 21:27
  • I think, No. Compiler can *assume* that, *p will initialize it later. because this is an unsafe code*. Anyway this is not a exact fit to SO. – Eser Sep 04 '15 at 21:29

2 Answers2

1

When you deal with unsafe code in C#, you are basically telling the compiler, don't warn me about things, I've got this. So the compiler is only doing what you have told it.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • maybe. compiler only suspend that error when taking the address of `i`. not only using unsafe suspends the error. – M.kazem Akhgary Sep 04 '15 at 21:30
  • 3
    @Daniel, if you just remove `int* p = &i`. compiler will warn you. so it is unrelated with `unsafe` code. Compare `int i;int* p = &i; int j = i; ` with `int i; int j = i; ` – Eser Sep 04 '15 at 22:06
  • @Eser the compiler might be smart enough to optimize out `unsafe code`. – Daniel A. White Sep 04 '15 at 23:21
0

The code is perfectly valid as you are not using unassigned variable but you are taking its pointer.

The last line is valid as well as it is not usage of unassigned variable but dereferencing pointer.

This is why c# is managed language until you switch into unsafe mode.

The zero of 'j' is probably caused by debug mode.

Aik
  • 3,528
  • 3
  • 19
  • 20