0

I have read that following code would be invalid and should issue error:

double rates[5] = {88.99, 100.12, 59.45, 183.11, 340.5};
const double locked[4] = {0.08, 0.075, 0.0725, 0.07};
double * pnc = rates; // valid
pnc = locked; // not valid
pnc = &rates[3]; // valid

pnc is pointer-to-double and user can't change data through it. Although, I compiled program adding this chunk of code:

printf("%f\n", *pnc);   
*pnc = 1000.0;
printf("%f\n", *pnc);

Visual Studio Community gave me warning C4090 (different 'const' qualifiers), but executed without problems. When I run program, output looks like this:

0.080000
1000.000000

Why can I do it even in case it has to be forbidden?

MrDonMatti
  • 74
  • 5
  • 1
    Because it is C, and you can basically do whatever you want to if you try hard enough. – OldProgrammer Oct 31 '16 at 23:09
  • @OldProgrammer Yeah, it is really similar question to my doubts. Thanks for showing! – MrDonMatti Oct 31 '16 at 23:15
  • @MrDonMatti - A compiler can easily transform your code `*pnc = 1000.0; printf("%f\n", *pnc);` into `printf("%f\n", 1000.0);` and produce the result *without* modifying any constants. Still undefined behavior though. – Bo Persson Nov 01 '16 at 10:20

1 Answers1

1

The const qualifier is only to prevent compilation (or at least create a warning) if a dev modify an element that, in the program logic, should be constant. In fact, once it is compiled, in almost every case, const or not const, the generated program will be the same.

Here there is a warning, but because you are a crazy dev (we are all crazy sometime), you ignored it.

If you want, you can even do

pnc = (double *)locked;

UPDATE: You can look at this link for more details. It also speak about C++, but it's very interesting :) http://www.gotw.ca/gotw/081.htm

Ludonope
  • 963
  • 9
  • 14