0

What is the difference between a an array being passed as a constant versus the array values being constants?

When passing an array of pointers to a function when every value is a constant:

`void display(Fraction* const ar[], int size);`

everything works fine but when the array is a constant

`void display(const  Fraction* ar[], int size);` 

the compiler gives the following error when calling the function:

`error C2664: 'display' : cannot convert parameter 1 from 'Fraction *[3]' to 'const Fraction *[]'`

main:

int main()
{
    Fraction* fArray[3];
    Fraction* fOne = new Fraction();
    Fraction* fTwo = new Fraction();
    Fraction* fThree = new Fraction();
    fOne->num = 8;
    fOne->den = 9;
    fTwo->num = 3;
    fTwo->den = 2;
    fThree->num = 1;
    fThree->den = 3;
    fArray[0] = fOne;
    fArray[1] = fTwo;
    fArray[2] = fThree;
    display(fArray, 3);

    system("pause");
    return 0;
}
1
  • I assume you do not intend to modify ar inside display, so you could just add const everywhere, i.e. Fraction const * const ar[] which is then a legal conversion. Commented Jul 18, 2018 at 6:02

1 Answer 1

3

This is a FAQ.

Note that const T* a[] means T const* a[], i.e. it's not the array itself that you have declared const; instead you have declared an array of pointers to const items.

Essentially, if the language provided an implicit conversion T**T const**, then you could inadvertently attempt to change something that was originally declared const:

int const     v = 666;
int*          p;
int**         pp = &p;
int const**   ppHack = pp;    //! Happily not allowed!

*ppHack = &v;    // Now p points to the const v...
Sign up to request clarification or add additional context in comments.

2 Comments

May I ask for an update on the link, please? I am googling in paralell, but this would help.
@DavidTóth: Done. The FAQ is now at isocpp.org.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.