In first case type of passed parameter is
char*
(actually it is char[4], but it is not important here). It can be passed to both types of func. It can be modified without any fear
In second case passed parameter is string literal of type
const char*
. It can only be received by
const char* /const char[]
functions. It cannot be changed and any attempt to do so will lead to UB and possible crash.
If your compiler is adequate and properly configured, it won't let you do that (however I suppose, your compiler is not, as it allows you to use illegal
void main()
)
Basically if i do:
func( "asd" );
without using the const then that char [] created by "" ... where does that
go when function is called and where it stays while im in function? |
String literals are stored with program image in read only memory.
I assume that in const case the variable what i pass into function, in function
i would not have that same function but it's copy, am i right? |
Depends on how you pass it to the function:
1 2 3 4 5 6
|
some_function( int foo) // foo is a copy of passed variable you can change
some_function(const int foo) // foo is a copy of passed variable you cannot change
//Reference to variables are essentually variables themselves
some_function( int& foo) // foo is a reference to passed variable you can change
some_function(const int& foo) // foo is a reference to passed variable you cannot change
|
When you pass something to function it creeates new variable of type indicated in function argument list and initializes it with passed value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
With pointers (your case) it is different. What const in different places means:
//You can change x (can point it to another variable)
//You can change value it points to.
int* x;
//You can change x (can point it to another variable)
//You cannot change value it points to.
const int* x;
//You cannot change x (it always points to same variable)
//You can change value it points to.
int* const x;
//You cannot change x (it always points to same variable)
//You cannot change value it points to.
const int* const x;
|