Is it possible to declare several variables in C ++ and immediately assign the same value? Example:

int a, b, c, d = 0; 

So that all variables are equal 0 .

    3 answers 3

    To declare several variables and then assigning the same value to them does not constitute a problem. You can write for example

     int a, b, c, d; a = b = c = d = 0; 

    However, if you want to initialize variables when they are declared, you will have to initialize each variable separately. for example

     int a = 0, b = 0, c = 0, d = 0; 

    or

     int a = 0, b = a, c = a, d = a; 

    A simple declaration in C ++ is defined as follows (7 Declarations)

    The simple-declaration

     attribute-specifier-seqopt decl-specifier-seqopt init-declarator-listopt; 

    where init-declarator-list is defined as (8 Declarators)

    init-declarator-list:

     init-declarator init-declarator-list , init-declarator 

    init-declarator:

     declarator initializeropt 

    That is, each declarator (for simplicity: a declared identifier) ​​in the list has its own initializer.

      You can use initialization from a compound object , which appeared in c ++ 17:

       #include <array> auto [a, b, c, d] = std::array<int, 4>(); 

      Or, more generally, to initialize with different values:

       auto [a, b, c, d] = std::array<int, 4>{{ 1, 2, 3, 4 }}; 

      Such a variant is most likely compiled by the compiler into the same code as when using the explicit manual initialization of the form:

       int a = 1; int b = 2; int c = 3; int d = 4; 

      However, it seems to me easier and more correct to immediately use an array, rather than individual dissimilar variables.

        You can still do something like this:

         struct vars { int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p; vars() { ZeroMemory(this,sizeof(vars)); } }; 
        • What is ZeroMemory ? - AnT
        • one
          @ANT function from WinAPI. Clears bytes at the specified address. - gbg
        • 2
          @gbg: I think it would be possible not to use ZeroMemory , but simply declare an instance of the structure as vars v = {}; . - VladD