Array element type const

it is stated in the standard that an array of const elements has a different type than an array of non-constant elements? Here is my code and output of VC2010 and GCC4.8.0.

Thanks.

#include <iostream> #include <typeinfo> #include <ios> int main(){ int arr_a[] = {1, 2}; int const arr_b[] = {3, 4}; // or const int arr_b[] = {3, 4}; std::cout << typeid(arr_a).name() << "\n"; std::cout << typeid(arr_b).name() << "\n"; std::cout << "Same type: " << std::boolalpha << (typeid(arr_a) == typeid(arr_b)) << ".\n"; } int [2] int const [2] Same type: false. A2_i A2_i Same type: true. 
+6
source share
2 answers

The C ++ 11 standard actually says (3.9.3 / 1) (emphasis added)

[...] Qualified or cv-unqualified versions of a type are different types ; however, they must have the same understanding and alignment requirements

with the following accuracy:

The same representation and alignment requirements imply interchangeability as arguments to functions, return values ​​from functions, and non-static data are members of unions

+2
source

As indicated, typeid (). name () is not a great choice because the result is determined by the implementation. Try the following:

 #include <iostream> using namespace std; void array_function(const int a[]) { cout << "const int a[]" << endl; } void array_function(int a[]) { cout << "int a[]" << endl; } int main() { const int carray[] = { 1, 2, 3}; int array[] = { 1, 2, 3}; array_function(carray); array_function(array); } 

It will show you that the compiler can tell the difference. (Type is different.)

0
source

Source: https://habr.com/ru/post/948542/


All Articles