4 ms·
C is a simple language with some pearls and a lot of corner cases. For the corner cases "C. Puzzle Book" by Alan R. Feuer it's a funny read with a lot of oh-oh
by pietrofmaggi 16y ago
C is a simple language with some pearls and a lot of corner cases.
For the corner cases "C. Puzzle Book" by Alan R. Feuer it's a funny read with a lot of oh-oh moments.
For the pearls... well I can give you a couple:
- sizeof() macro is a good friend
- ISO C99 <stdint.h> introduces Exact-width integer types http://en.wikipedia.org/wiki/Stdint.h http://en.wikipedia.org/wiki/Stdint.h
- SeriousGuy 16y agothanks for the tips! One interesting use of sizeof i remember in my C++ project was to override new and delete operators where a void pointer is passed and sizeof is used to keep track of how much memory is allocated/deallocated.
- pietrofmaggi 16y agoOne interesting usage of sizeof() is to calculate the dimension of an array at compile time: #define dim(x) (sizeof(x) / sizeof(x[0])) and this is handy for static arrays with dimension defined by its data, likes: static const struct { someEnum_t enCommand; void (*Fxn)(stCommands_t *a_psCommand); } m_stCmdMap[] = { {CMD_SD_FREESPACE, _sdFreeSpace}, {CMD_SD_DISK_INFO, _sdDiskInfo}, {CMD_SD_FORMAT, _sdFormat}, } When you add a new array elements, it just keep the stuffs going calculating it at any recompilation: for (i=0; i<dim(m_stCmdMap); i++) { if (m_stCmdMap[i].enCommand == stCmdLocal.enCommand) { m_stCmdMap[i].Fxn(&stCmdCopy); break; } } Another useful macro to work with structs is offsetof(), its incredibly usefull when you have to port some code to different compilers/target with different alignments and paddings.