57. Register Callback Counter

#include <iostream>
using namespace std;

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

    int count = 0;

    // Lambda callback captures count by reference and increments it
    auto callback = [&count]() {
        count++;
    };

    for (int i = 0; i < n; i++) {
        callback();
    }

    cout << count;
    return 0;
}

Explanation & Logic Summary

  • The counter must be modified inside the callback, so count is captured by reference.
  • The problem forbids explicitly writing the callback’s type.
  • Using auto allows the compiler to infer the lambda’s type safely.
  • Each callback invocation increments count by one.
  • After calling the callback n times, the final value of count is printed.

Firmware Relevance & Real-World Context

  • Callbacks are heavily used in firmware for timers, GPIO interrupts, and scheduler hooks.
  • Lambdas allow callbacks to retain local state without global variables.
  • Type inference (auto) avoids verbose and non-portable callback declarations.
  • This pattern is common in modern Embedded C++ codebases targeting microcontrollers and RTOS-based systems.

 

 

 

 

Loading...

Input

0

Expected Output

0