4 ms·
Unrelated to the actual topic, but I believe there is a copy-paste bug in the first sample: const char *getCountry(int cc) { if(cc == 1) return "A1
by throwaway744678 5y ago
Unrelated to the actual topic, but I believe there is a copy-paste bug in the first sample:
const char *getCountry(int cc) {
if(cc == 1) return "A1";
if(cc == 2) return "A2";
if(cc == 3) return "O1";
if(cc == 4) return "AD";
if(cc == 5) return "AE";
if(cc == 6) return "AF";
if(cc == 7) return "AG";
if(cc == 1) return "AI";
...
if(cc == 252) return "YT";
if(cc == 253) return "ZA";
if(cc == 254) return "ZM";
if(cc == 255) return "ZW";
if(cc == 256) return "XK";
if(cc == 257) return "T1";
return "UNKNOWN";
}
This will never return "AI" (Anguila, as it seems!)
- klohto 5y agoFull example doesn't have this mistake, so I would assume it's not in production :) https://godbolt.org/z/KWYEW3d9s https://godbolt.org/z/KWYEW3d9s
- tuesdayrain 5y agoIf that was javascript you could make it return "AI" with the right `valueOf` call - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- crazypython 5y agoWouldn't the compiler optimize this to an array lookup? static const char* countries[257]; Or even: static const char countrycodes[514]; return countrycodes[i * 2];
- dahfizz 5y agoDoesn't look like it. Each case is a compare and jump: https://godbolt.org/z/KWYEW3d9s https://godbolt.org/z/KWYEW3d9s
- ChrisSD 5y agoTurn the gcc version up to 11.
- nitwit005 5y agoPlaying around a bit, it does seem that clang will do so: https://godbolt.org/z/1czW91bMM https://godbolt.org/z/1czW91bMM A presentation on algorithm improvements popped up when looking into it (2015): https://llvm.org/devmtg/2015-10/slides/Wennborg-SwitchLowering.pdf https://llvm.org/devmtg/2015-10/slides/Wennborg-SwitchLoweri...
- deleted 5y ago[deleted]
- jfrunyon 5y agostatic const char countrycodes[514]; return countrycodes[i * 2]; Err... each of the strings is 3 bytes long.