# Setting and restoring variables (or: when you wish \`block()\` worked differently…)

**URL:** https://discourse.cmake.org/t/setting-and-restoring-variables-or-when-you-wish-block-worked-differently/10333
**Category:** Usage
**Created:** [March 9, 2024, 12:53am UTC](https://discourse.cmake.org/t/setting-and-restoring-variables-or-when-you-wish-block-worked-differently/10333 "2024-03-09T00:53:56Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![dabrahams](https://discourse.cmake.org/user_avatar/discourse.cmake.org/dabrahams/32/4265_2.png) [@dabrahams](https://discourse.cmake.org/u/dabrahams)
#### Post date: [March 9, 2024, 12:53am UTC](https://discourse.cmake.org/t/setting-and-restoring-variables-or-when-you-wish-block-worked-differently/10333/1 "2024-03-09T00:53:56Z")

</div>

I find this idiom awkward. I use `if(YES)` just to get some visual indication of the scope-like behavior here. Is there a better way to do this?

```cmake
# Not using block() here because FetchContent_MakeAvailable typically causes dependency-specific
# global variables to be set, and I'm not sure to what extent they may be needed
if(YES)
  set(saved_BUILD_EXAMPLES ${BUILD_EXAMPLES})
  set(saved_BUILD_EXAMPLES ${BUILD_EXAMPLES})

  set(BUILD_EXAMPLES NO)
  set(BUILD_TESTING NO)

  FetchContent_MakeAvailable(ArgumentParser SwiftSyntax)

  set(BUILD_EXAMPLES ${saved_BUILD_EXAMPLES})
  set(BUILD_EXAMPLES ${saved_BUILD_EXAMPLES})
endif()

```

---

<div class="post-metadata">

### Author: ![dabrahams](https://discourse.cmake.org/user_avatar/discourse.cmake.org/dabrahams/32/4265_2.png) [@dabrahams](https://discourse.cmake.org/u/dabrahams)
#### Post date: [March 9, 2024, 4:53am UTC](https://discourse.cmake.org/t/setting-and-restoring-variables-or-when-you-wish-block-worked-differently/10333/2 "2024-03-09T04:53:40Z")

</div>

…And my copy/paste error above shows exactly why something better is needed. It should have been:

```auto
# Not using block() here because FetchContent_MakeAvailable typically causes dependency-specific
# global variables to be set, and I'm not sure to what extent they may be needed
if(YES)
  set(saved_BUILD_EXAMPLES ${BUILD_EXAMPLES})
  set(saved_BUILD_TESTING ${BUILD_TESTING})

  set(BUILD_EXAMPLES NO)
  set(BUILD_TESTING NO)

  FetchContent_MakeAvailable(ArgumentParser SwiftSyntax)

  set(BUILD_EXAMPLES ${saved_BUILD_EXAMPLES})
  set(BUILD_TESTING ${saved_BUILD_TESTING})
endif()

```

---

<div class="post-metadata">

### Author: ![ben.boeckel](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/b/ea5d25/32.png) [@ben.boeckel](https://discourse.cmake.org/u/ben.boeckel)
#### Post date: [April 10, 2024, 9:43pm UTC](https://discourse.cmake.org/t/setting-and-restoring-variables-or-when-you-wish-block-worked-differently/10333/3 "2024-04-10T21:43:39Z")

</div>

No, I’m not aware of an obviously better way to do this. A `macro` would do, but then you have a macro.
