Question on const

Hi,

I have question on const variables in function parameters

ex:
void foo(const int& i)
{

}

Apart from we cannot modify 'i' variable, does it have significance with respect to compiler optimization?

Regards,
nkumar
Since it is a reference being passed to a function, not really.
closed account (3hM2Nwbp)
Regarding compiler optimization, I'm not sure, but the const qualifier can extend the life of a temporary variable passed into your function.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<string>

void f1(std::string& theString) { }

void f2(const std::string& theString) { }

int main()
{
  const char* charPointer = "Stringy";
  f1((std::string)charPointer); // <- Compiler might complain about passing a temporary
  f2((std::string)charPointer); // <- Compiler shouldn't complain
  return 0;
}


Be sure to correct me if I'm wrong in this example, I can't test it right now.
Hi firedraco,

I did not mean reference (it was just an example), in fact any const member in function parameter.

Regards,
Kumar
Topic archived. No new replies allowed.