Skip to content

Instantly share code, notes, and snippets.

@pusewicz
Created October 6, 2025 03:38
Show Gist options
  • Select an option

  • Save pusewicz/8c13315dacbe5fb4f93c1d7bf93543c8 to your computer and use it in GitHub Desktop.

Select an option

Save pusewicz/8c13315dacbe5fb4f93c1d7bf93543c8 to your computer and use it in GitHub Desktop.
Block-style cf_draw
#pragma once
#define _CF_CONCAT(a, b) a##b
#define _CF_VAR(line) _CF_CONCAT(_cf_guard_, line)
/**
* @brief Scoped drawing context macro
*
* @details Creates a scoped block that automatically calls cf_draw_push() on
* entry and cf_draw_pop() on exit. This ensures proper pairing of push/pop
* calls even in the presence of early returns or exceptions.
*
* The macro uses a for-loop trick to achieve RAII-like behavior:
* - cf_draw_push() is called before the loop body executes
* - Loop body runs exactly once
* - cf_draw_pop() is called when exiting the scope
*
* @note Uses __LINE__ to generate unique variable names, preventing collisions
* @warning Cannot be used multiple times on the same line (generates same
* variable name)
* @note Safe for nested usage across different lines
*
* @code
* void render() {
* cf_draw() {
* draw_rectangle(0, 0, 100, 100);
* draw_circle(50, 50, 25);
* }
* }
*
* void complex_render() {
* cf_draw() {
* set_color(RED);
* draw_background();
*
* cf_draw() {
* set_color(BLUE);
* draw_overlay();
* }
*
* draw_border();
* }
* }
* @endcode
*/
#define cf_draw() \
for (auto _CF_VAR(__LINE__) = (cf_draw_push(), 1); _CF_VAR(__LINE__); \
_CF_VAR(__LINE__) = 0, cf_draw_pop())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment