Why are char[] and char* as typedefs different, but sometimes… not?

前端 未结 3 1168
遥遥无期
遥遥无期 2020-12-31 09:30

The following observation arose as I was following this question about char[] and char* differences.

#include 

typ         


        
3条回答
  •  耶瑟儿~
    2020-12-31 09:55

    I changed the code so that we could see how calling a f2 changes the type. Before the call the variables are of different type. After the call they have become same

        typedef char ar[];
    typedef char* pr;
    void f2(ar x, pr y)
    {
        cout << is_same::value << '\n'; //same type
    }
    
    int main()
    {
        ar data = "data";
        pr ptr = data;
        cout << is_same::value << '\n'; // different
        f2(data,ptr);
        return 0;
    }
    

    the output is 0 0 .As @jthill, @Dyp and @keith Thompson says this is because of decaying of the array to pointer.

提交回复
热议问题