Why we use const keyword in function parameter

I know we use const keyword to make pointer to constant, constant pointer, etc. But what's the purpose of using const keyword in function parameters.

1
2
3
4
5
bool check(const char* word)
{
    // TODO
    return false;
}


Please explain
The function promises not to change the data referenced by the pointer, and the compiler enforces this guarantee.
@LB But how it is beneficial
I already explained the benefits: the function makes a promise that you can rely on because the compiler enforces it. You don't have to worry about this function changing the data you give it.
One benefit:
The benefit of const correctness is that it prevents you from inadvertently modifying something you didn’t expect would be modified. You end up needing to decorate your code with a few extra keystrokes (the const keyword), with the benefit that you’re telling the compiler and other programmers some additional piece of important semantic information — information that the compiler uses to prevent mistakes and other programmers use as documentation. - https://isocpp.org/wiki/faq/const-correctness


A second benefit: const correctness widens the range of the function:

1
2
3
4
5
6
7
8
9
10
11
12
bool foo( char* cstr ) ;

bool bar( const char* cstr ) ;

int main()
{
    const char hello[] = "hello world" ;

    // foo(hello) ; // *** error: range of foo is restricted to modifiable (non volatile) c-style strings

    bar(hello) ; // fine: range of bar is all (non volatile) c-style strings
}
@ati here is a example using pointers:

pointers are not always initialized by default , to force initialization sometimes we do like this :

//.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "SceneObject.h"

struct Frustum;

class CameraObject
	: public virtual SceneObject
{

private:

	Frustum  *const m_frustum;

public:

	CameraObject();

	virtual ~CameraObject();

	virtual SceneObject::Object getObjectType() const override;

	static SceneObject::Object getStaticObjectType();

	Frustum  *const getFrustum() const;

};


//.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "CameraObject.h"

#include "Frustum.h"

CameraObject::CameraObject()
: SceneObject()
, m_frustum(new Frustum)
{
	//first computation of the frustum
	m_frustum->compute();
}
CameraObject::~CameraObject()
{
	delete m_frustum;
}
SceneObject::Object CameraObject::getObjectType() const
{
	return SceneObject::Object::CAMERA_OBJECT;
}
SceneObject::Object CameraObject::getStaticObjectType()
{
	return SceneObject::Object::CAMERA_OBJECT;
}
Frustum  *const CameraObject::getFrustum() const
{
	return m_frustum;
}


if you remove in the cpp the line
,m_frustum(new Frustum)
you will get an error.

Did that help a little ?
@Ericool: did you respond to the wrong thread or something? This thread is about const
@LB
Frustum *const m_frustum;
Topic archived. No new replies allowed.