Tuesday, January 7, 2025

Designated Initializer in C vs CPP

 C supports a powerful designated initializes specially for Array & Struct in any order. Doesn't depend on declaration order. It was introduced since 1999. Here is an example: 


c example
The output of the above program is:

output

C supports nested, mixed designated initialization: 




C++ initiated this designated initialization in c++20 in year 2020 and we can say it as a limited version. It depends on declaration order of the struct variables. We can not use any order like C language. Also we can not use it for Array :(

Only we can skip some middle variables which will be initialized by zero but we must need to follow it's original declaration order.

Here is an example of c++20:
cpp example

C++ supports mixed type to designated initialization but doesn't support nested type :(




Rules for Designated Initializers (CPP):

1. Each data member can have only one designator.  
2. Designators are applicable only for aggregate initialization.  
3. Nested designators are not allowed.  
4. Regular initialization cannot be combined with designators in the same expression.  
5. It is not mandatory to specify all data members in the initialization expression.  
6. Designators can reference only non-static data members.  
7. The order of designators in the initialization expression must match the order of data members in the class declaration.  

Advantages of Designated Initialization

    Readability: By specifying the exact data member being initialized, the designator ensures clarity and eliminates the possibility of errors.
   Flexibility: It allows you to skip initializing certain data members and depend on their default values instead.
   Compatibility with C: A similar initialization syntax is widely used in C99 (with even more relaxed rules). The C++20 feature enables writing nearly identical code, facilitating code sharing between C and C++.
   Standardization: While compilers like GCC and Clang already provided extensions for this feature, its inclusion in the standard ensures uniform support across all compilers.











No comments:

PC Magazine Tips and Solutions

PC World: Latest Technology News

PCWorld.com - Most Popular Downloads of the Week