C/C++ Programming Tips and Tricks

Every once in a while I found some C/C++ tips and tricks. This page is going to be the repository of those tips and tricks.

Constexpr specifier declares that it is possible to evaluate the expression at compile time:
1. Constexpr function
2. Constexpr constructor
3. Constexpr variable
Initialization of constexpr MUST happen at compile time (const variable can defer at runtime). Constexpr implies const and const implies static. If constexpr variable is in the header, every translation unit will get its own copy. Since C++17, inline keyword can be added to variables (and constexpr variables) that means there should only be one single copy in all translation units (this also allows to declare non-const variable in header file).

Fast insertion to std::map/std::unordered_map
std::unordered_map > m;
auto [iter, succeed] = m.emplace( key, nullptr );
if ( succeed )
  iter->second = std::make_unique();

Creating C++ function similar to printf()
inline std::string StringFormat(const char *format, Args... args)
 size_t size = std::snprintf(nullptr, 0, format, args...) + 1; // Extra space for '\0'

 auto buf = std::make_unique< char[] >(size);
 std::snprintf(buf.get(), size, format, args...);

 return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside

Getting class member size and offset
struct MyStruct
    int field0;
    char field1;
sizeof( MyStruct::field0 )
offsetof( MyStruct, field0 )

Print the first n characters with printf()
const char* pStr = "C Tips and Tricks.";
printf( "%.*s\n", 5, pStr);  // This will print "C Tips"

Specifying enum type
enum EnumAsByte : unsigned char { ... };
enum EnumAsUnsignedShort : unsigned short { ... };


Popular posts from this blog

GDC 2015 Links

D3D11 Compute Shader - Part 1

Mapping Square Texture to Trapezoid / Quadrilateral