Use of ‘const’ in Functions Return Values

本文探讨了在C/C++中使用'const'关键字作为函数返回值类型的意义。通过实例说明了如何避免运行时错误,并解释了不同类型的'const'在函数返回值中的作用。

Use of 'Const' in Function Return Values

为什么要在函数的返回值类型中添加Const?

1、Features

Of the possible combinations of pointers and ‘const’, the constant pointer to a variable is useful for storage that can be changed in value but not moved in memory.

Even more useful is a pointer (constant or otherwise) to a ‘const’ value. This is useful for returning constant strings and arrays from functions which, because they are implemented as pointers, the program could otherwise try to alter and crash. Instead of a difficult to track down crash, the attempt to alter unalterable values will be detected during compilation.

For example, if a function which returns a fixed ‘Some text’ string is written like

    char *Function1()
    { return “Some text”;}

then the program could crash if it accidentally tried to alter the value doing

    Function1()[1]=’a’;

whereas the compiler would have spotted the error if the original function had been written

    const char *Function1()
    { return "Some text";}

because the compiler would then know that the value was unalterable. (Of course, the compiler could theoretically have worked that out anyway but C is not that clever.)

2、Examples

Use of 'const' in Function Return Values

#include <iostream>
using namespace std;
const char * function()
{
    return "some Text";
}

const int function1()
{
    return 1;
}

int  main()
{
    
    char * h = function(); //1 does not compile
    int h = function1();   //2 works

    return 0;
 }

function returns a pointer to const char* and you can't just assign it to a pointer to non-const char (without const_cast, anyway). These are incompatible types.
function1 is different, it returns a constant int. The const keyword is rather useless here - you can't change the returned value anyway. The value is copied (copying doesn't modify the original value) and assigned to h.

For function to be analogue to function1, you need to write char* const function(), which will compile just fine. It returns a constant pointer (as opposed to a non-const pointer to a const type).

转载于:https://www.cnblogs.com/xuanyuanchen/p/7443350.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值