-2

How come that output of following programm is "pankaj", I was expecting a compilation error like "can not modify a constant string"

#include<iostream>
using namespace std;

void fun(const char *a)
{
  a = "pankaj";
  cout  << a;
}

int main()
{
  const char *ptr = "GeeksforGeeks";
  fun(ptr);
  return 0;
}
alexbt
  • 16,415
  • 6
  • 78
  • 87
pankaj kushwaha
  • 369
  • 5
  • 20
  • You didn't modify the *string* you modified the *pointer* that *points* to the *string* to make it point to a different *string*. – Galik Jun 05 '15 at 11:41

3 Answers3

2

In C function parameters are passed by value. This means that inside fun() you're working with a copy of a, not the original variable. This means, that you're not modifying ptr inside fun(). Only it's copy stored locally in a. This variable, i.e. a, is not visible outside fun() and neither are any modifications made to it.

Now, const char *a means that a is a pointer that points to a location in memory containing read-only characters. This means, that you cannot modify those characters. You can, however, modify what a is pointing to and that's what you're doing.

banach-space
  • 1,781
  • 1
  • 12
  • 27
  • Your first para is not really relevant as it is just fine to modify the original variable too – M.M Jun 05 '15 at 12:13
  • @MattMcNabb It's definitely less relevant than I originally thought it was. Thank you! I'll leave there though. It's already been up-voted in this form and this question is marked as [duplicate] anyway. – banach-space Jun 05 '15 at 12:35
1

You´re not modifying any string, just the parameter a.
First, it´s a pointer to the passed value, then it´s a pointer to a string constant in your program.
You can´t change the passed string data, but changing the pointer is fine.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
1

ptr is a pointer to a char array. The pointer is const, but not the content pointed by him. U can change the content by doing:

ptr = "AnotherThing"

But You cannot change the memory direction the pointer is ponting to.

If you try this, you will get an error:

*ptr = 'C';

Tirma
  • 664
  • 5
  • 16