Use of ‘const’ in Functions Return Values

Oct 19, 2010 at 3:15pm
Hy,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;
 }


My question:
Why does the program compile if I comment out the line marked 1 but it does not compile if I comment out the line marked 2? What is the sense of const in function1?

Many thanks!
dziadgba


Oct 19, 2010 at 3:33pm
The const keyword means you're not meant to change the value, trying to assign it to a non-const variable thus produces an error.
Oct 19, 2010 at 3:38pm
But int h works, Pax.

I'm not fully sure, but maybe one or more of the reasons why the conversion from const char* to char * has been deprecated have something to do with it...

-Albatross
Last edited on Oct 19, 2010 at 3:39pm
Oct 19, 2010 at 3:45pm
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).
Oct 19, 2010 at 3:58pm
Albatross: the int h is implicitly making a copy.
Topic archived. No new replies allowed.