Const int als Array größe



  • Ich bin heute über eine Merkwürdigkeit gestolpert und wollte mal Wissen wie man
    es richtig macht:

    Normal:

    const int ArrayMax =10;
    int MyArry[ArrayMax];
    

    Das sollte der Compiler noch Akzeptieren

    Wenn ich das jetzt in eine Bib stecke würde das wie folgt aussehen:

    foo.hpp:
    #pragma once
    
    extern const int ArrayMax;
    extern int MyArray[ArrayMax];
    
    foo.cpp:
    #include "foo.hpp"
    
    const int ArrayMax = 10;
    int MyArray[ArrayMax]={};
    

    Hier meckert der Compiler weil in der Forward zu MyArray const int ArrayMax = 0 ist.

    Alternativ

    foo.hpp:
    #pragma once
    
    extern const int ArrayMax =10;
    extern int MyArray[ArrayMax];
    
    foo.cpp:
    #include "foo.hpp"
    
    int MyArray[ArrayMax]={};
    

    Aber das Mag der Compiler auch nicht wirklich und gibt mir den Hinweis das ArrayMax bereits in anderen Bibs vorhanden ist.

    Was funktioniert aber unschön ist:

    foo.hpp:
    #pragma once
    #define ArrayMax 10 //Will ich nicht da das normalerweise Berechnet wird
    extern int MyArray[ArrayMax];
    
    foo.cpp:
    #include "foo.hpp"
    
    int MyArray[ArrayMax]={};
    

    Wie würde man das richtig machen?
    ich habe in der Zwischenzeit beide Varianten als richtig gehört aber keine lässt sich ohne fehler Kompilieren...



  • Muss das wirklich so ein veraltetes Array sein?



  • Arraygrößen müssen Compiletimekonstanten sein...



  • Genau, nimm std::vector und verzichte auf das globale ArrayMax.


  • Mod

    Möglichkeit 1 (so wurde das schon immer gemacht): Verzichte auf extern für ArrayMax
    Nichtlokale const-Variablen haben internal Linkage sofern sie nicht explizit extern deklaraiert werden:

    foo.hpp:
    #pragma once
    
    const int ArrayMax=10; // internal linkage
    extern int MyArray[ArrayMax];
    
    foo.cpp:
    #include "foo.hpp"
    
    int MyArray[ArrayMax]={};
    

    In den meisten Fällen, wird das Programm nur den Wert, nicht aber die Adresse von ArrayMax benötigen.

    Möglichkeit 2 (C++17) - verwende inline

    foo.hpp:
    #pragma once
    
    extern inline const int ArrayMax=10;
    extern inline int MyArray[ArrayMax]={};
    

Anmelden zum Antworten