r/C_Programming • u/space_junk_galaxy • 4d ago
Question Design choice with enums and strings
I'm working on a C minecraft clone, and I've been refactoring a bunch of my block code. Previously a "block" was just an enum, I essentially "hardcoded" the list of blocks in the game itself. Part of the refactor is using a JSON file for defining blocks and their metadata. However, because of this, I've now reached a weird place. The JSON defines the ID as a string. The enum that was BLOCK_GRASS is now a string in the JSON as "BLOCK_GRASS".
The design question I have is should I be referencing a string in my code, and doing comparisons with strings? Or do I need to have some sort of intermediate mapping of string IDs -> enum IDs. The latter seems kind of wasteful since it just means all the benefits of the JSON config file went away.
Not sure what the general consensus is. The strings are going to be in the data section anyways so I don't think I'm being wasteful with allocations here.
15
u/catbrane 3d ago
I'd keep strings in the JSON and map them to and from enum values on load and save. The point of the JSON file is to isolate save files from C enum values, so it's still worthwhile.
You could use pointers to static strings and just pointer compare, since your C compiler will common up all strings like
"BLOCK_GRASS", but it would be so easy to make a small mistake and have a very tricky bug. Ints are safer and easier to debug.7
u/tstanisl 4d ago
The main problem is that comparison of strings requires indirection and looping and difficult to predict branching. All of those are very slow on modern CPUs. Comparing tiny `int` can often be allow to eliminate branching by using masking technique. So if you care about performance, use integer identifiers.
In some cases, string comparison can be replaced with comparison of pointers but you must first make sure that all potentially compared strings comes from the same pool with no duplicates.
6
u/aeropl3b 3d ago
I am not entirely sure your problem. JSON is a serialization format, not a C representation.
If the idea is you are going to permit dynamic block types via JSON config, then I would use a registery of block types, and a handle to the block meta data. The handle can just be an int that points to an offset in an array of block data.
A block instance could then be a handle, coordinate data, durability, etc. Effectively the same as the current enum approach, but the enums are now dynamicly assigned ints.
4
u/Agitated_Ad_5989 4d ago
Save them as the integer the enum value is representing
1
u/RussianHacker1011101 3d ago
This doesn't directly answer your question, but I'd like to make a suggestion. Use SQLite rather than a JSON file. You'll inevetably want need to modify this file. It could grow to be very large. You also might want a serialization format for "saved game" or for a level builder. You can also easily pivot between string ids and integer ids. And you could import your JSON file directly into SQLite and query it (in order to import it into a table).
2
u/Rabbitical 3d ago
Your JSON storage method and your internal program operation need not and should not be the same at all. The point of JSON is to be human readable, the point of your enums is to bridge the gap between human readable and integers which make the computer happy. Once you load your blocks from JSON, you use string comparisons to assign enum values and then never deal in strings again.
2
u/GoblinsGym 3d ago
One trick that you can use is limit string names to 4 or 8 characters, then you can do a quick integer compare.
For internal stuff I use a textual format like this:
name value
Names are 4 character codes, cast to a 32 bit integer and have a big switch statement...
2
u/Maxwelldoggums 3d ago
You could use a hash of the string at runtime to convert it to an arbitrary integer.
1
u/Jonatan83 3d ago
It's hard to answer without knowing how you are using it. How often will you be comparing? Maybe you can compare hashes instead (and assume or verify that there are no collisions).
1
u/8d8n4mbo28026ulk 3d ago edited 3d ago
Intern your strings and you can just compare them by their identity. If your code compares IDs, you'd want to intern them anyway, since the config file might contain bogus values.
1
u/RealisticDuck1957 3d ago
If the intent is to get away from hard coded block types (a good idea), the data file defining types should have a number ID associated with each type. A string may also be defined for human interface.
1
u/Gold-Part4688 3d ago
if the strings stay statically in memory throughout, and are only defined once - can you just compare their pointers?
1
u/Traveling-Techie 3d ago
Think about generating your code with a program using configuration files.
1
u/wsppan 2d ago
The point of Json is to have a format you can serialize data structures in your code in order to pass around to different services via REST API calls.or, in your case, between your code and the file system. You should not conform your codes data structures to what is used in the serialized Json. Create serialize/desensitize libraries and use them.
0
u/tastygames_official 3d ago
ooh, don't use JSON. It's not very performant: https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/
Just save it as an integer and use a custom file format instead of JSON. You can use an 8-but unsigned int and have 255 block types, then your file format might have something like
byte 1: block type
2-5: float x pos
6-9: float y pos
10-13: float z pos
14: uint8_t how many characters are in the next string
15-?: string of characters for the name or whatever
then just use a series of fread()s to read all the data.
Now if you don't have that many block types, you can even use a nibble or even just a few bits for the block type and then use the other bits for other flags so you can still hit that 8-bit alignment.
0
u/-moron 3d ago edited 3d ago
Scrap the global enum to save compile time when modifying or adding block types. You could use YAML or something so you can store the block ID keys as integers instead of strings. Or just store the blocks in a list in the JSON file and use the index. It's best to work with integers over strings when possible.
0
u/LaggerFromRussia 3d ago
If you configuring the blocks in json, why do you need enum IDs in the code? What you want is probably a hashmap of string->block. For saving the world you can do the same trick as minecraft: each chunk contains palette - array of block states (including string ID), chunk saves blocks as indexes in it's palette. (Actually, it's a little trickier: chunk->sections->block_list+block_states->data+palette.)