53. Constexpr ADC Temperature Table

#include <iostream>
using namespace std;

// Compile-time temperature lookup table
constexpr int TEMP_TABLE[6] = { -40, -10, 20, 50, 80, 120 };

int main() {
    int idx;
    cin >> idx;

    cout << TEMP_TABLE[idx];

    return 0;
}

Explanation & Logic Summary

  • TEMP_TABLE is declared as constexpr, so it is evaluated entirely at compile time
  • The table is stored in Flash / ROM, not RAM
  • Runtime execution performs a constant-time (O(1)) lookup
  • No arithmetic or floating-point computation occurs at runtime
  • This guarantees deterministic execution time

Firmware Relevance & Real Embedded Meaning

In memory-constrained embedded systems (8 KB–32 KB MCUs):

  • constexpr tables save RAM by residing in Flash
  • Lookup tables eliminate costly runtime math
  • Immutable data prevents accidental modification
  • Compilers can aggressively optimize constant access

This pattern is commonly used in:

  • Thermistor temperature conversion
  • Battery voltage-to-percentage mapping
  • Display gamma correction
  • Motor control profiles
  • Sensor calibration data

Using a non-constexpr array would:

  • Consume RAM
  • Require runtime initialization
  • Allow unintended modification
  • Reduce optimization opportunities

For these reasons, constexpr lookup tables are standard practice in production embedded firmware.

 

 

 

 

Loading...

Input

0

Expected Output

-40