banner
cells

cells

为美好的世界献上 code

Q186

Q186#

#include <iostream>
#include <typeinfo>

void takes_pointer(int *pointer) {
    if (typeid(pointer) == typeid(int[])) {
        std::cout << 'a';
    }
    if (typeid(pointer) == typeid(int *)) {
        std::cout << 'p';
    }
}

void takes_array(int array[]) {
    if (typeid(array) == typeid(int[])) {
        std::cout << 'a';
    }
    if (typeid(array) == typeid(int *)) {
        std::cout << 'p';
    }
}

int main() {
    int *pointer = nullptr;
    int array[1];

    takes_pointer(array);
    takes_array(pointer);

    std::cout << (typeid(int *) == typeid(int[]));
}

Answer#

click to see answer pp0

Explain#

First let's look at takes_pointer(array);. What happens here is usually referred to as the array "decaying" to a pointer.

"An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”."

array is of type "array of 1 int", which converts to a prvalue (temporary) of type "pointer to int".

So in void takes_array(int array[]), the type of array is adjusted to be pointer to int.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.