Home Common Problem Can functions be nested in definition but not in nested calls?

Can functions be nested in definition but not in nested calls?

Feb 02, 2021 pm 04:28 PM
function Nested calls

Wrong, functions can be nested calls but cannot be nested defined. In C language, all functions are parallel, that is, they are independent of each other when defining functions. One function is not subordinate to another function, that is, functions cannot be nested in definition, but they can call each other, but they cannot call the main function. .

Can functions be nested in definition but not in nested calls?

The operating environment of this tutorial: Windows 7 system, C99 version, Dell G3 computer.

Wrong, functions can be nested calls but cannot be nested defined.

C Language Function

A function is a piece of code that can be reused to independently complete a certain function. It can Receive data passed by the user, or not. Functions that receive user data must specify parameters when defining them. Functions that do not receive user data do not need to be specified. Based on this, functions can be divided into parameterized functions and parameterless functions.

The process of encapsulating a code segment into a function is called function definition.

Definition of function

If the function does not receive data passed by the user, it can be defined without parameters. As shown below:

dataType  functionName(){
    //body
}
Copy after login

If the function needs to receive data passed by the user, then it must be defined with parameters. As shown below:

dataType  functionName( dataType1 param1, dataType2 param2 ... ){
    //body
}
Copy after login
  • dataType is the return value type, which can be any data type in C language, such as int, float, char, etc.

  • functionName is the function name, which is a type of identifier. The naming rules are the same as identifiers. The parentheses ( ) after the function name cannot be missing.

  • dataType1 param1, dataType2 param2... is the parameter list. A function can have only one parameter or multiple parameters, separated by . Parameters are essentially variables, and the type and name must be specified when defining. Compared with the definition of a parameterless function, the definition of a parameterized function only has one more parameter list.

  • body is the function body, which is the code that the function needs to execute and is the main part of the function. Even if there is only one statement, the function body must be surrounded by { }.

  • If there is a return value, use the return statement in the function body to return it. The type of data returned must be the same as dataType.

    return is a keyword in C language, which can only be used in functions to return processing results.

Example:

#include <stdio.h>
int sum(){
    int i, sum=0;
    for(i=1; i<=100; i++){
        sum+=i;
    }
    return sum;
}
int main(){
    int a = sum();
    printf("The sum is %d\n", a);
    return 0;
}
Copy after login

Run result:

The sum is 5050
Copy after login

Function cannot be nested definition, main is also a function definition, so sum should be placed outside main. Functions must be defined first and then used, so sum must be placed before main.

Note: main is a function definition, not a function call. When the executable file is loaded into the memory, the system starts execution from the main function, that is, the system will call the main function we defined.

Tutorial recommendation: "c language tutorial video"

Function Call

The so-called function call (Function Call ), that is, using an already defined function. The general form of function call is:

functionName(param1, param2, param3 ...);
Copy after login

functionName is the function name, param1, param2, param3... is the actual parameter list. Actual parameters can be constants, variables, expressions, etc. Multiple actual parameters are separated by commas.

In C language, there are many ways to call functions, for example:

//函数作为表达式中的一项出现在表达式中
z = max(x, y);
m = n + max(x, y);
//函数作为一个单独的语句
printf("%d", a);
scanf("%d", &b);
//函数作为调用另一个函数时的实参
printf( "%d", max(x, y) );
total( max(x, y), min(m, n) );
Copy after login

Nested calling of functions

Functions cannot be nested definitions , but calls can be nested, that is, a call to another function is allowed during the definition or call of one function.

[Example] Calculate sum = 1! 2! 3! ... (n-1)! n!

Analysis: You can write two functions, one for calculating factorial and one for Used to calculate the cumulative sum.

#include <stdio.h>
//求阶乘
long factorial(int n){
    int i;
    long result=1;
    for(i=1; i<=n; i++){
        result *= i;
    }
    return result;
}
// 求累加的和
long sum(long n){
    int i;
    long result = 0;
    for(i=1; i<=n; i++){
        //在定义过程中出现嵌套调用
        result += factorial(i);
    }
    return result;
}
int main(){
    printf("1!+2!+...+9!+10! = %ld\n", sum(10));  //在调用过程中出现嵌套调用
    return 0;
}
Copy after login

Operating results:

1!+2!+...+9!+10! = 4037913
Copy after login

The call to factorial() appears in the definition of sum(), the call to sum() appears during the call to printf(), and printf () is also called by main(), and their overall calling relationship is:

main() --> printf() --> sum() --> factorial()
Copy after login

If a function A() calls another function B() during the definition or calling process, then we call it A() is the calling function or main function, and B() is called the called function.

When the calling function encounters the called function, the calling function will pause, and the CPU will execute the code of the called function; after the called function completes execution, it will return to the calling function. The status continues to execute.

The execution process of a C language program can be considered as the mutual calling process between multiple functions, which form a simple or complex calling chain. The starting point of this chain is main(), and the end point is also main(). When main() has finished calling all functions, it will return a value (such as return 0;) to end its own life, thereby ending the entire program.

A function is a code block that can be reused. The CPU will execute the codes one by one. When encountering a function call, the CPU must first record the address of the next code in the current code block (assuming the address is 0X1000), then jump to another code block, and then come back to continue executing the code at 0X1000 after the execution is completed. The whole process is equivalent to the CPU taking a break, temporarily putting down the work in hand to do something else, and then continuing the previous work after finishing it.

For more knowledge about computer programming, please visit: Programming Video! !

The above is the detailed content of Can functions be nested in definition but not in nested calls?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.