0

I know you will say its a duplpicate but belive me i read alot of articles about this but i still cant understand what is the diffrence so im giving two examples.
1.

int strlen(const char* string)
{
   int i = 0;
   while (string[i] != '\0')
   {
       ++i;
   }
   return i;
}

2.

int strlen(char* string)
{
   int i = 0;
   while (string[i] != '\0')
   {
       ++i;
   }
   return i;
}

Main:

int main() 
{
    char str[] = "Hello";
    cout << strlen(str) << endl;
}

The second will work and wont get errors while the first wont.

Rokni
  • 67
  • 13

1 Answers1

1

Case 1: you can not change value of string, it's read-only. It's used to prevent function from changing value of parameter (Principle of least privilege)

Case 2: you can change value of string.

Also, check that link from comments.

Stefan Golubović
  • 1,225
  • 1
  • 16
  • 21