*************
C++
topic: call functions
*************
Calling functins in a program is everywhere.
Beautiful design is really beautiful. It looks exquisite. It is none of this topic's business.
Come back to functions. As is mentioned before, the basic struction of function is
- // basic structure of function
- 返回类型 函数名 (参数类型 参数名,参数类型 参数名,···)
- {
- 函数体
- }
复制代码
So write a code as an example.
- #include <iostream>
- using namespace std;
- int g_c;
- void add(int a, int b)
- {
- g_c = a + b;
- }
- int main()
- {
-
- return 0;
- }
复制代码 int g_c here is a global variable. In another void function, add function can be called.
case 1: call directly
just use the function name to call the function.
- #include <iostream>
- using namespace std;
- int g_c;
- void add(int a, int b)
- {
- g_c = a + b;
- }
- int main()
- {
- // 直接调用add函数
- add(13, 38);
- return 0;
- }
复制代码
case 2 : use undirectly result after calling the add function.
sometimes it may happen that the resultt after used delaying being called.
- #include <iostream>
- using namespace std;
- int g_c;
- void add(int a, int b)
- {
- g_c = a + b;
- }
- void checkResult()
- {
- // 检查 g_c 的值
- cout << "Result: " << g_c << endl;
- }
- int main()
- {
- add(13, 38); // add 被调用,结果存入 g_c
- checkResult(); // 检查 g_c 的值
- return 0;
- }
复制代码
case 3 : to provude a g_c interface
- #include <iostream>
- using namespace std;
- int g_c;
- void add(int a, int b)
- {
- g_c = a + b;
- }
- void Plus()
- {
- add(13, 38); // 调用 add 函数
- }
- int get_g_c()
- {
- return g_c;
- }
- int main()
- {
- Plus(); // 通过 Plus 函数调用 add
- int result = get_g_c(); // 通过 get_g_c 函数获取 g_c 的值
- cout << "g_c = " << g_c << endl; // 输出 g_c 的值
- printf("result = %d\n", result); // 输出 result 的值
- return 0;
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |