Home >Backend Development >C++ >Can C Functions Be Nested?

Can C Functions Be Nested?

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 07:54:14492browse

Can C   Functions Be Nested?

Nested Functions in C

Question: Is it possible to define functions within other functions in C ?

Answer:

Modern C (C 11 or later):

Yes, you can create nested functions using lambdas. Lambdas allow you to define anonymous functions that can capture local variables within their scope.

int main() {
    auto print_message = [](std::string message) {
        std::cout << message << "\n";
    };
    print_message("Hello!");
}

C 98 and C 03:

In C 98 and C 03, directly defining functions within functions is not supported. However, you can use the following technique:

  1. Define a local class within the outer function.
  2. Declare static functions within the local class.
int main() {
    struct X {
        static void a() {}
    };
    X::a();
}

While this allows you to create functions inside functions, it's considered a workaround and should be used sparingly due to its potential for obscurity in code comprehension.

The above is the detailed content of Can C Functions Be Nested?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn