Beamdog / nwn-issues

Neverwinter Nights: Enhanced Edition Technical Bug Tracker
http://nwn.beamdog.com
31 stars 1 forks source link

"case" label statements in switch can have mismatched types #605

Closed jd28 closed 8 months ago

jd28 commented 8 months ago

Specifics

If needed, describe the bug


// Somewhere in an include ...
const int SOME_GLOBAL_CONSTANT_1 = 1;
const string SOME_GLOBAL_CONSTANT_2 = "Test";

// .......

void main()
{
  int integer_target; // unspecified value
  switch(integer_target) {
     default: break;
     case SOME_GLOBAL_CONSTANT_1: // ...
       break;
     case SOME_GLOBAL_CONSTANT_2: // ...
       break;
  }
}

This compiles. I understand how the string cases are implemented, but I don't think this is intended behavior?

mtijanic commented 8 months ago

Yes, this is expected behavior, documented somewhat in nwscript.nss entry for HashString():

// Returns the 32bit integer hash of sString
// This hash is stable and will always have the same value for same input string, regardless of platform.
// The hash algorithm is the same as the one used internally for strings in case statements, so you can do:
//    switch (HashString(sString))
//    {
//         case "AAA":    HandleAAA(); break;
//         case "BBB":    HandleBBB(); break;
//    }
// NOTE: The exact algorithm used is XXH32(sString) ^ XXH32(""). This means that HashString("") is 0.
int HashString(string sString);

Actual relevant impl at https://github.com/niv/neverwinter.nim/blob/master/neverwinter/nwscript/native/scriptcompfinalcode.cpp#L969