Use of ‘const’ in Functions Return Values

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).

posted @ 2017-08-28 13:02  xiulug  阅读(205)  评论(0编辑  收藏  举报