Handmade Hero » Forums » Code » Re-defied variable bug
Stas.L
Stas Lisetsky
18 posts
1 project

Ex-php dev. Working on a 2d graphics editor

#3159 Re-defied variable bug
2 years, 5 months ago Edited by Stas Lisetsky on March 29, 2015, 12:33 a.m.

Hey everone! It's a small thing but I still wanted to know.

So I was working on code from day 34 and this happened:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
internal uint32
GetTileValue(world *World, tile_chunk *TileChunk, uint32 TestTileX, uint32 TestTileY)
{
    uint32 TileChunkValue = 0;

    if(TileChunk) {
        uint32 TileChunkValue = GetTileValueUnchecked(World, TileChunk, TestTileX, TestTileY);
    }

    return(TileChunkValue);
}


See how I have 2 uint32 TileChunkValue definitions? TileChunkValue was 0 all the time because of that. Value from the GetTileValueUnchecked() call was completely ignored. And my tilemap was just empty.

Why C did that? And why compiler ignored that? (I have all same compiler keys as Casey had).

That's a shameful thing, but took me a long time to find it. Any ways to prevent that other than stepping through the code?

None
mmozeiko
Mārtiņš Možeiko
1476 posts
1 project
#3160 Re-defied variable bug
2 years, 5 months ago Edited by Mārtiņš Možeiko on March 29, 2015, 2:10 a.m.

Compiler Warning C4189 would help you there, but Casey turned it off in build.bat. If you want to turn it on, remove "-wd4189" from cl.exe arguments.

GCC and clang has much better warning for this situation - "-Wshadow" it will warn not because you are not using initialized variables, but it will warn if you have variables with same name in some outer scope.

Why this is allowed? Because somebody decided it can be useful in some situations:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
void f()
{
  int x = 1;
  ... use x here
  {
    int x = 2;
    .. use x with value 2 here
    {
      .. and here
    }
  }
  .. use x with value 1 here
}
Stas.L
Stas Lisetsky
18 posts
1 project

Ex-php dev. Working on a 2d graphics editor

#3164 Re-defied variable bug
2 years, 5 months ago

Ok, now I remember that. I guess I'll have to enable that warning for now. (And rewatch compiler keys day) I have a feeling that I'll be making this mistake over and over agian, because I type-in all the code along with Casey (to learn his speed and productivity) - thus making losts of 'copy-pasta' errors.

Thanks mmozeiko!

None