C++中函数的调用

*************

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值