Select lines in which assignment and initialisation is correct in C++:
int main() {
    char c;

    char *p0 = &c;
    const char *p1 = &c;  // 1
    char *const p2 = &c;  // 2
    const char *const p3 = &c;  // 3

    const char **p;

    p = &p0;  // 4
    p = &p1;  // 5
    p = &p2;  // 6
    p = &p3;  // 7
}
Explanation
C++ allows implicit conversion of variable to the constant (T-> const T) and pointer to the variable into the pointer to the constant (T* -> const T*) for the same type T. Type pairs (T, const T) and (T*, const T*) are considered to be different, therefore:
- Line // 1 is correct since initialization of pointer to constant using a pointer to a variable (T* -> const T*) doesn’t require explicit type conversion
- Line // 2 is correct, since initialisation of constant using variable (T -> const T) doesn’t require explicit type conversion.
- Line // 3 is correct since initialization of constant pointer to constant using variable pointer to the constant (T* -> const T*const) doesn’t require explicit type conversion. - Line // 4 is incorrect because here an attempt is made to assign a pointer to a variable of one type (T *) to a pointer to a variable of another type (const T *), which requires an explicit type conversion.
- Line // 5 is correct because this is the usual assignment of variables of the same type.
- Line // 6 is incorrect because here an attempt is made to assign a pointer to a variable of one type (T) to a pointer to a variable of another type (const T).
- Line // 7 is incorrect because here an attempt is made to assign a pointer to a variable of one type (T *) to a pointer to a variable of another type (const T * const).

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести