jeudi 28 mars 2019

What is the correct initializer for a non-static 2D array?

Visual Studio allows: int a[3][3] = { 0 }; for BOTH local variable and non-static class variable. However, GCC only allows this for local variables, but requires int a[3][3] = { {0} }; for class variable initialization. Is GCC too restrictive or VS to permissive?

#include <iostream>
using namespace std;

class InitArray {
 public:
   InitArray();
   void PrintArray() const;
 private:
   int a[3][3] = { 0 };       // compiles in Visual Studio 2017, but not GCC
                              // modify to = { {0} }; to compile in GCC
InitArray::InitArray() {
   PrintArray();
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         a[i][j] = 1;
      }
   }
}

void InitArray::PrintArray() const {
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         cout << a[i][j] << " ";
      }
      cout << endl;
   }
}

int main() {
   InitArray A;
   A.PrintArray();
   int a[3][3] = {0};          // OK in BOTH compilers
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         cout << a[i][j] << " ";
      }
      cout << endl;
   }

   return 0;
}

Aucun commentaire:

Enregistrer un commentaire