search
HomeBackend DevelopmentC#.Net TutorialChapter 6 C++: Function Basics and Applications

Chapter 6 Function

A function is a named block of code that executes the corresponding code by calling the function.

Function Basics

  • Execute the function by call operator(call operator). Its form is a pair of parentheses.

  • The call of the function completes two tasks (as follows). At this time, the execution of the main calling function (calling function) is temporarily interrupted, and the called function (called function) )Begin execution.

    • Initialize the formal parameters corresponding to the function with actual parameters.

    • Transfer control to the called function.

  • return statement:

    • Return the value in the return statement

    • Move control from the called function back to the calling function

Local object

  • Names have scope, objects haveLifecycle(lifetime)

  • Automatic object(automatic object): This object is created when the control path of the function passes through the variable definition statement. Destroy it when the end of the block in which it is defined is reached.

  • Local static object: It is initialized when the program execution path passes through the object definition statement for the first time, and is not destroyed until the program terminates.

    • Define local variables as static to obtain, for example:
      <br>//Statistical function count_calls () How many times has it been called <br>size_t count_calls () <br>{ <br>static size_t ctr = 0; //After the call is completed, this value is still valid <br>return ctr; <br>} <br>int main () <br>{ <br>for (size_t i = 0; i != 10; i) <br>cout return 0; <br>} <br>

Function declaration

  • Also called function prototype(function prototype)

  • The three elements of a function (return type, function name, formal parameter type) describe the interface of the function, and the formal parameter name can be omitted in the function declaration.

  • Functions should be declared in the header file and defined in the source file.

  • Separate compilation

Parameter passing

If the formal parameter is a reference type, it will be bound to the corresponding actual parameter; otherwise, copy the value of the actual parameter and assign it to the formal parameter.
- If the value of a reference parameter does not need to be modified, it is best to declare it as a constant reference.

main: Handle command line options

Assuming that the main function is located in the executable file prog, we can pass the following options to the program:

prog -d -o ofile data0

These commands pass two executable files The selected formal parameters are passed to the main function:

int main(int argc, char *argv[]) {...}
//或:
int main(int argc, char **argv) {...}

When the actual parameters are passed to the main function, the first element of argv points to the name of the program or an empty string, and the next elements are passed to the command line at a time actual parameters. The last pointer will only drop the element value and is guaranteed to be 0.
- Take the above command line as an example:

argc = 5;argv[0] = "prog";argv[1] = "-d";argv[2] = "-o";argv[3] = "ofile";argv[4] = "data0";argv[5] = 0;

Function with variable parameters

  • C 11 new standard provides two methods to write functions that can handle different numbers of instances Parameter function:

  1. All actual parameters are of the same type, and a standard library type named initializer_list can be passed.

  2. If the actual parameter types are different, we can write a special function called a variable parameter template.

  • #C There is also a special parameter type: ellipsis. You can use it to pass a variable number of actual parameters. This function is generally only used for interface programs that interact with C functions.

  • initializer_list formal parameter

    • The type is defined in the header file with the same name

    • Provides the following operations:
      <br>initializer_list<t> lst; //Default initialization, empty list of T type elements <br>initializer_list<t> lst{a ,b,c...}; <br>//lst has the same number of elements as the initial value; the elements of lst are copies of the corresponding initial values; the elements in the list are const <br>lst2(lst) <br> lst2 = lst //Copying or copying an initializer_list object will not copy the elements in the list; after copying, the original list and the copy elements are shared<br>lst.size() //The number of elements in the list<br>lst.begin( ) //Returns a pointer to the first element in lst<br>lst.end() //Returns a pointer to the next position of the last element in lst<br></t></t>

    Return types and return statements

    • References return lvalues, and other return types get rvalues.

    • List initialization return value: The new C 11 standard stipulates that a function can return a list of values ​​surrounded by curly braces.

    The return value of the main function main

    • Allows the main function to have no return value (if not, the compiler implicitly inserts return 0)

    • 返回0表示执行成功,其他值依机器而定。

    • 为了使返回值与机器无关,cstdlib头文件定义了两个预处理变量,分别表示成功和失败:
      <br>return EXIT_FAILURE; <br>return EXIT_SUCCESS; <br>//因为它们是预处理变量,所以既不能在前面加上std::,也不能在using声明里出现。 <br>

    返回数组指针

    1. 使用类型别名
      <br>typedef int arrT[10];   //arrT是一个类型别名,它表示的类型是含有10个整数的数组 <br>using arrT = int[10];   //与上一句等价 <br>arrT* func(int i);      //func返回一个指向含有10个整数的数组的指针 <br>

    2. 声明一个返回数组指针的函数,形式如下
      <br>Type (*function(parameter_list)) [dimension] <br>//Type表示返回的数组指针指向的数组元素类型 <br>//dimension表示数组的大小 <br>//例如: <br>int (*func(int i)) [10]; <br>

    3. 使用尾置返回类型(C++11)
      <br>auto func(int i) -> int(*)[10]; <br>

    4. 使用decltype
      <br>int odd[] = {1,3,5,7,9}; <br>int even[] = {0,2,4,6,8}; <br>decltype(odd) *arrPtr(int i) <br>{ <br>    return (i % 2) ? &odd : &even;  //返回一个指向数组的指针 <br>} <br>

    函数重载

    如果同一作用域内的几个函数名字相同但形参列表不同,我们称之为重载(overloaded)函数

    • 不允许两个函数除了返回类型外其他所有要素都相同。

    • 重载与作用域:一旦在当前作用域中找到了所需的名字,编译器就会忽略掉外层作用域中的同名实体。

    特殊用途语言特性

    介绍三种函数相关的语言特性:默认实参、内联函数、constexpr函数。

    默认实参

    • 调用包含默认实参的函数时,可以包含该实参,也可以省略该实参。

    • 一旦某个形参被赋予了默认值,它后面所有的形参都必须有默认值。

    内联函数(inline)

    调用函数一般比求等价表达式的值要慢,内联函数可避免函数调用的开销。
    - 将函数指定为内联函数,通常就是将它在每个调用点上“内联地”展开。

    constexpr函数

    • 函数的返回类型和所有的形参类型都得是字面值类型。

    • 函数中必须有且只有一条return语句。

    • constexpr函数被隐式地指定为内联函数。

    内联函数和constexpr函数通常定义在头文件中

    调试帮助

    程序可以包含一些用于调试的代码,但这些代码只在开发程序时使用。当应用程序编写完成准备发布时,要先屏蔽掉调试代码。这种方法用到两项预处理功能:assert和NDEBUG。

    assert预处理宏

    #include <cassert>assert(expr);//首先对expr求值,//如果表达式为假(即0),assert输出信息并终止程序的执行。//如果表达式为真(即非0),assert什么也不做。//例如:对一个文本进行操作的程序可能要求所给定单词的长度都大于某个阈值。assert(word.size() > threshold;

    NDEBUG预处理变量

    • assert的行为依赖于一个名为NDEBUG的预处理变量的状态。如果定义了NDEBUG,则assert什么也不做。默认状态下没有定义NDEBUG,此时assert将运行执行时检查。

      • 使用#define语句定义NDEBUG,从而关闭调试状态。

      • 很多编译器都提供了命令行选项使我们可以定义预处理变量。
        <br>$ CC -D NDEBUG main.C   #微软编译器中用 /D <br>

    • 这只是调试程序的辅助手段,不能代替真正的逻辑检查,也不能代替程序本应该包含的错误检查。

    • 除了assert以外,也能使用NDEBUG编写自己的条件调试代码:

    //如果定义了NDEBUG,#ifndef和#endif之间的代码将被忽略void print(const int ia[], aize_t size)
    {    #ifndef NDEBUG
            //_ _func_ _是编译器定义的一个局部静态变量,用于存放函数的名字,它是const char的一个静态数组。
            cerr << _ _func_ _ << "array size is " << size << endl;    #endif}

    除了_ _ func _ _之外,还有其它四个名字:

    _ _FILE_ _ 存放文件名的字符串字面值
    _ _LINE_ _ 存放当前行号的整型字面值
    _ _TIME_ _ 存放文件编译时间的字符串字面值
    _ _DATA_ _ 存放文件编译日期的字符串字面值

    函数指针

    bool lengthCompare(const string &, const string &);//pf指向一个函数,该函数的参数是两个const string的引用,返回值是bool类型。注意圆括号必不可少bool (*pf) (const string &, const string &);    //未初始化

    当我们把函数名作为值使用时,该函数自动地转换成指针

    pf = lengthCompare;     //pf指向名为lengthCompare的函数pf = &lengthCompare;    //等价赋值语句,&是可选的

    调用该函数:

    //此三个调用等价bool b1 = pf("hello", "goodbye");bool b2 = (*pf)("hello", "goodbye");bool b3 = lengthCompare("hello", "goodbye");

    参考:C++Primer第五版

    相关文章:

    第四章C++:表达式概念-运算符的应用

    Chapter 5C: Introduction to statements

    The above is the detailed content of Chapter 6 C++: Function Basics and Applications. 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
    Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

    C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

    C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

    .NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

    The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

    Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

    Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

    Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

    C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

    C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

    C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

    .NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

    The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

    The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

    The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

    The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

    See all articles

    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 Article

    Hot Tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment