3 ms·
> Declaring a variable or parameter of type T as const T means, roughly, that the variable cannot be modified. I would add "... cannot be modified through that
by quietbritishjim 4y ago
> Declaring a variable or parameter of type T as const T means, roughly, that the variable cannot be modified.
I would add "... cannot be modified through that pointer". (Yes, in fairness, they did say "roughly".) For example consider the following:
void foo(int* x, const int* y)
{
printf("y before: %d\n", *y);
*x = 3;
printf("y after: %d\n", *y);
}
This will print two different values if you have `int i = 1` and you call `foo(&i, &i)`. This is the classic C aliasing rule. The C standard guarantees that this works even under aggresive optimisation (in fact certain optimisations are prevented by this rule), whereas the analogous Fortrain wouldn't be guaranteed to work.
- pm2222 4y ago*y in both printf, right?
- vardump 4y agoA small detail: you probably meant printf("y before: %d\n", *y);
- quietbritishjim 4y agoOops you're right! Fixed now thanks.
- pafje 4y agoYou already know this, but I would add that under strict aliasing rules, this is only valid because x and y point to the same type. The most common example is when y is float* and someone tries to access its bitwise representation via an int*. (Please correct me if I'm wrong) https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8 https://gist.github.com/shafik/848ae25ee209f698763cffee272a5...