-2

I still don't understand what is the difference between these two code i mean if we put const

keyword in front of data type parameter in function what happened to my our code

#include <iostream>
using namespace std;

void function1(const int x);

int main(){

};

And if we don't put const keyword what happened to our code?

#include <iostream>

using namespace std;

void function2( int x);

int main(){


};
  • 7
    Try to do `x = 5;` in both functions and you will see the difference. – Yksisarvinen Jul 27 '21 at 15:11
  • In your function _declaration_, it has no effect. Your two code samples are equivalent. In the function's _definition_, the variable is const. – Drew Dormann Jul 27 '21 at 15:17
  • @keamvireak `const` lets you express you are not going to modify that parameter within the function; the compiler will make sure you don't do it: https://godbolt.org/z/zY8f1rPcY – rturrado Jul 27 '21 at 15:17
  • The answers [here](https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters) may shed some light. – Drew Dormann Jul 27 '21 at 15:22
  • In the code examples provided, the `const` in the declaration as used in this code has no affect on the code, and there is no difference. The `const` does not even affect the signature of the declaration (i.e., the mangled name is the same). – Eljay Jul 27 '21 at 15:25

1 Answers1

0

The const keyword prevents a variable from being modified.

It mostly used to prevent an object that is passed by reference from being modified. It can also prevent mistakes at compile time like writing = instead of == in boolean statements.

In your case, the variable is passed by value and not by reference. In both function declarations, the variable inside the function is a copy of the variable you pass to that function. This means that even if you change a variable that is passed by value, its value will only change inside the scope of that function.

Relate to this article about scoping.

Wahalez
  • 489
  • 1
  • 6
  • 22