0

I am beginner to C++, so my question is probably very naive. For instance, during runtime I decide to initialize a variable using std::optional, i.e. the variable is only defined under certain conditions. My idea is now: Ignore all the following code where the variable will be part of it.

Line 34: std::optional<unsigned int> may_defined_or_not = ...;
...
//Line 45 should be ignored when compiling the code
Line 45: may_defined_or_not += 2;
//Even more complicated: Ignore this whole if-block
Line 57: if(may_defined_or_not) {...}

Is something like that possible at all? If so, I would appreciated getting some keywords to look for! Tnak you very much!

Simon
  • 325
  • 1
  • 6
  • If the decision whether or not to initialize the variable is made at runtime, how do you expect it to decide to ignore line 45 or not when compiling? – Nathan Pierson Jul 09 '21 at 11:40
  • maybe `if` is what you need to read about. As Nathan pointed out, the compiler cannot do that for you, but you can do it at runtime – 463035818_is_not_an_ai Jul 09 '21 at 11:42
  • Of course if can be applied here. But I thtought there is may some special C++ class which can deal with that also during runtime. So something like "a hidden reference" when initializing – Simon Jul 09 '21 at 11:45
  • Why write the code at all if you want the compiler to ignore it? – molbdnilo Jul 09 '21 at 11:56
  • when the compiler can convince themself that `may_defined_or_not` never holds a value when you reach `if(may_defined_or_not) {...}` then it might remove that code as part of an optimization. However, thats not a reliable mechanism, and actually its not needed, because, as molbdnilo says, if you know the code will never be executed, why write it in the first place? – 463035818_is_not_an_ai Jul 09 '21 at 12:05

0 Answers0