Home > Backend Development > C++ > Can C Functions Be Nested, and How Has This Evolved Across Different Standards?

Can C Functions Be Nested, and How Has This Evolved Across Different Standards?

DDD
Release: 2024-12-20 08:27:10
Original
431 people have browsed it

Can C   Functions Be Nested, and How Has This Evolved Across Different Standards?

Nested Functions in C

In the context of C , the question arises whether functions can be defined within other functions.

Modern C

In C 11 and later versions (C 14, C 17), nested functions are possible through the use of lambda expressions. Lambdas can be defined within functions and behave like anonymous functions:

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

  for (int i = 0; i < 10; i++) {
    print_message("Hello!");
  }

  return 0;
}
Copy after login

C 98 and C 03

In C 98 and C 03, nested functions are not directly supported. However, a similar effect can be achieved through the use of local classes with static member functions:

int main() {
  struct X {
    static void a() {}
  };

  X::a();

  return 0;
}
Copy after login

While this approach provides a semblance of nested functions, it is not as straightforward as using lambdas in modern C .

The above is the detailed content of Can C Functions Be Nested, and How Has This Evolved Across Different Standards?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template