Consider this function:

double find_distance (const stud &pnt_1,
const stud &pnt_2);

stud is a defined structure.

What is the point of calling pnt_1 and pnt_2 by reference if 'const' is included at the begginning, making the value remain constant? I mean, when we call by reference, its only to change the variable being called, right?

Hope my question makes sense :lol:

Thx

when you call by reference you also greatly reduce the overhead of creating the callstack of the function.
The amount of stack memory needed will go down from the size of the struct you pass as a parameter to the size of a pointer to that struct.
If the struct is really large (say several kb) that can greatly increase performance and reduce the memory footprint of your application.
By passing a reference you also remove the need to create (underwater) a copy of your data whenever you call a function, another way in which the overhead of creating your callstack is created.

Therefore passing a const reference is almost always preferable if you're going to pass something that's larger than the size of a pointer in your operating system (usually 32 bits in current operating systems).

IMHO ive never HAD to use the const keyword, though i see it in a LOT of & and * parameters so it can only be a good thing. in basic terms it is probably ESSENTIAL for the & operator as that will return the address of the variable, something which really should be constant you might think.... :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.