Thread: Zero Initialization of struct, C++

  1. #1
    Registered User
    Join Date
    Dec 2010
    Location
    Trinidad, CO (log cabin in middle of nowhere)
    Posts
    148

    Zero Initialization of struct, C++

    Say I have this struct...

    Code:
    struct SomeStruct
    {
     int a;
     int b;
     int c;
     int d;
    };
    My simple tests indicate this...

    Code:
    int main()
    {
     SomeStruct ss{0};
     ...
    
     return 0;
    }
    ...is equivalent to this...

    Code:
    int main()
    {
     SomeStruct ss = {0};
     ...
    
     return 0;
    }
    Is this kosher??? In my research I found reference to the 2nd, but not the first, i.e., ...

    Code:
    ss{0}

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,190
    Although I do not believe either conforms to any particular dietary laws, I do believe that they are essentially equivalent in the given context. However, you should get a warning about missing initializers if you are using a reasonable warning level (i.e., with g++ at least -Wall -Wextra).

    In modern C++, the best way to zero-init your POD struct is with empty braces and no equals sign.
    We live as it were by chance, and by chance we are governed. - Seneca

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,611
    In modern C++, the best way to zero-init your POD struct is with empty braces and no equals sign.
    Or better yet initialize the variables in the structure definition.

    Code:
    struct SomeStruct
    {
     int a{};
     int b{};
     int c = 0;
     int d = 0;
    };

  4. #4
    Registered User
    Join Date
    Dec 2010
    Location
    Trinidad, CO (log cabin in middle of nowhere)
    Posts
    148
    Thanks John and Jim. Appreciate it. Working on something, and the issue came up. My C++ is old, so I need to update.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fastest Initialization of a Struct
    By leeor_net in forum C Programming
    Replies: 5
    Last Post: 03-12-2009, 04:03 AM
  2. Pointer Initialization Within A Struct
    By SMurf in forum C Programming
    Replies: 15
    Last Post: 02-09-2009, 11:27 AM
  3. Struct Initialization
    By carrotcake1029 in forum C Programming
    Replies: 5
    Last Post: 05-06-2008, 02:27 PM
  4. Replies: 3
    Last Post: 08-22-2005, 01:18 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

Tags for this Thread