Home >Backend Development >C++ >Can C Functions Nest Within Other Functions?

Can C Functions Nest Within Other Functions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 22:40:10530browse

Can C   Functions Nest Within Other Functions?

Can Functions Nest Within Functions in C ?

In C , the answer to this question depends on the version of the language being used.

Modern C (C 11 and Later)

Yes, with lambdas:

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

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

C 98 and C 03

No, not directly. However, you can use static functions inside local classes as a workaround:

int main() {
  struct X {
    static void a() {}
    void b() {
      a();  // can call static member function inside non-static function.
    }
  };

  X::a(); // call the function from outside the class.

  X my_x;
  my_x.b(); // call the second function from outside the class.

  return 0;
}

Caution

In C 98 and C 03, using local classes and static functions to simulate nested functions is not a common practice and may be confusing to other developers.

The above is the detailed content of Can C Functions Nest Within Other Functions?. 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