Question about casting (relating to qsort and pointers to structures)

Printable View

Quote:


Correct?

Now, just to get a bit clearer on the syntax and the use of const, I tried running a few alternatives through gcc, with the following results:

Case 1
Code:

Word *nw1 = *(Word **)w1;
Result: Compiled without error and coincidentally or otherwise, program seemed to work.

Case 2:
Code:

Word *nw1 = *(Word const **)w1;
Result: gcc produces the following message: warning: initialization discards qualifiers from pointer target type

Case 3:
Code:

Word *nw1 = *(const Word **)w1;
Result: Same as Case 2
The form "const Word" and "Word const" are the same thing - you can put "const" on either side of the type, with the same effect. This form means that the pointer itself is a constant value, so you are not changing the pointer - this would be correct if you also put "const Word *nw1" - which would work fine for your code - you are just comparing the data inside your structure, so you CAN (should[1]) use "const Word *nw1".

So as a conclusion:
Code:

const Word *nw1 = *(const Word * const *)w1;
is the preferred code.

Quote:


In light of the above:

[1] Whilst some people would disagree, I think most would agree that WHENEVER POSSIBLE, const should be there.

--
Mats
  • 01-22-2008
    kuda
    I think that I've got it, or at least that I understand enough of it for now.
    My conclusion:

    Code:

    Word * nw1 = *(Word * const *)w1;
    w1 is cast as a const pointer, to a pointer to Word. It is then dereferenced using the * operator to match the type of nw1 i.e. pointer to Word. Since only the pointer w1 is const, it is acceptable for nw1 to access what it points to without nw1 itself needing to be const.

    Code:

    const Word * nw1 = *(Word const **)w1;
    Even though this might appear to cast w1 as ‘const pointer to pointer, of Word’, ‘Word const’ is the same as ‘const Word’ and w1 is actually cast as ‘pointer to pointer to, const Word’. Since w1 (which is not const in this case) ultimately points to type const Word, the compiler produces a warning if nw1 does not point to type const Word as well.

    Tick?
  • 01-23-2008
    matsp
    Yup, that's how it works.

    As I said earlier, you could add another const on either side of the equal sign, making the code more "const correct".

    --
    Mats
  • 01-23-2008
    kuda
    Thanks for all your help!

  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21