Significance of Lambda Function in C/C++

Lambda Function − Lambda functions are anonymous inline functions that don't require any implementation outside the scope where they are defined. They provide a concise way to write small functions directly at the point of use.

Lambda functions can also be stored in variables and treated as objects that can be called (called functors). When the compiler encounters a lambda function definition, it creates a custom object for that lambda.

Note: Lambda functions are a C++11 feature and are NOT available in C. They are part of the C++ standard, not C. In C programming, you would use function pointers to achieve similar functionality.

Syntax

[capture](parameters) -> return_type { function_body }

The syntax components are −

  • [ ] - Capture clause
  • ( ) - Parameters (Optional)
  • - Return type (Optional)
  • {...} - Function body

Example: Basic Lambda Function (C++)

Since lambda functions are C++ features, here's how they work −

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};
    
    // Lambda function to square each element
    for_each(numbers.begin(), numbers.end(), [](int &n) {
        n = n * n;
        cout << n << " ";
    });
    
    return 0;
}

C Alternative: Function Pointers

In C programming, we use function pointers to achieve similar functionality −

#include <stdio.h>

/* Function that squares a number */
int square(int x) {
    return x * x;
}

/* Function that applies operation to array */
void apply_operation(int arr[], int size, int (*operation)(int)) {
    for (int i = 0; i < size; i++) {
        arr[i] = operation(arr[i]);
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = 5;
    
    printf("Original: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\nSquared: ");
    
    /* Using function pointer (C way) */
    apply_operation(numbers, size, square);
    
    return 0;
}
Original: 1 2 3 4 5 
Squared: 1 4 9 16 25 

Key Differences

Feature C (Function Pointers) C++ (Lambda Functions)
Inline Definition No Yes
Capture Variables No (use globals/parameters) Yes
Anonymous No Yes
Standard C89+ C++11+

Conclusion

Lambda functions are a C++ feature that provides inline anonymous functions with variable capture capabilities. In C programming, function pointers serve a similar purpose but require separate function definitions. For C programmers wanting lambda-like behavior, function pointers are the standard approach.

Updated on: 2026-03-15T13:04:58+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements