Conditional compilation chooses which code is compiled, while normal variables still choose runtime data.

conditional compilation `#if` and `#ifdef` decide which source text is kept before compilation.

Conditional Compilation

count
conditional_compilation.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <string>

#define USE_SHORT_LABEL 1

int main() {
    int count = 3;

#if USE_SHORT_LABEL
    std::string label = "qty";
#else
    std::string label = "quantity";
#endif

    std::cout << label << "=" << count << std::endl;
    std::cout << "double=" << count * 2 << std::endl;
    return 0;
}
#include <iostream>
#include <string>

#define USE_SHORT_LABEL 1

int main() {
    int count = 1;

#if USE_SHORT_LABEL
    std::string label = "qty";
#else
    std::string label = "quantity";
#endif

    std::cout << label << "=" << count << std::endl;
    std::cout << "double=" << count * 2 << std::endl;
    return 0;
}
#include <iostream>
#include <string>

#define USE_SHORT_LABEL 1

int main() {
    int count = 6;

#if USE_SHORT_LABEL
    std::string label = "qty";
#else
    std::string label = "quantity";
#endif

    std::cout << label << "=" << count << std::endl;
    std::cout << "double=" << count * 2 << std::endl;
    return 0;
}
  1. count ← 3, label ← qty

    6int main() {7    int count→ 3 = 3; //@count=1, 689#if USE_SHORT_LABEL10    std::string label→ qty = "qty";11#else12    std::string label = "quantity";13#endif1415    std::cout << labelqty << "=" << count3 << std::endl;16    std::cout << "double=" << count3 * 2 << std::endl;17    return 0;18}
    outputqty=3
    double=6
  1. count ← 1, label ← qty

    6int main() {7    int count→ 1 = 1;89#if USE_SHORT_LABEL10    std::string label→ qty = "qty";11#else12    std::string label = "quantity";13#endif1415    std::cout << labelqty << "=" << count1 << std::endl;16    std::cout << "double=" << count1 * 2 << std::endl;17    return 0;18}
    outputqty=1
    double=2
  1. count ← 6, label ← qty

    6int main() {7    int count→ 6 = 6;89#if USE_SHORT_LABEL10    std::string label→ qty = "qty";11#else12    std::string label = "quantity";13#endif1415    std::cout << labelqty << "=" << count6 << std::endl;16    std::cout << "double=" << count6 * 2 << std::endl;17    return 0;18}
    outputqty=6
    double=12

Follow the Choice

  1. USE_SHORT_LABEL is defined as 1.
  2. The #if USE_SHORT_LABEL branch is kept.
  3. The compiled label is qty.
  4. count starts at 3.
  5. The program prints qty=3 and double=6. | count | compiled label | first output | second output | | ---: | --- | --- | --- | | 1 | qty | qty=1 | double=2 | | 3 | qty | qty=3 | double=6 | | 6 | qty | qty=6 | double=12 |

Exercise: conditional_compilation.cpp

Reproduce qty=3 and double=6, then use count 1 and 6 to predict qty=1 with double=2 and qty=6 with double=12.