Skip to content
Fix Code Error

How to initialize a struct in accordance with C programming language standards

March 13, 2021 by Code Error
Posted By: cringe

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;
  double stuff;
} MY_TYPE;

void function(void) {
  MY_TYPE a;
  ...
  a = { true, 15, 0.123 }
}

Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?

Update I ended up having a static initialization element where I set every subelement according to my needs.

Solution

In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Edit: Other members are initialized as zero: “Omitted field members are implicitly initialized the same as objects that have static storage duration.” (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

Answered By: philippe

Related Articles

  • create pascol voc xml from csv
  • Where do I find the current C or C++ standard documents?
  • What is the worst programming language you ever worked with?
  • I do not use TBB, but I get linker errors related to TBB
  • Callback functions in C++
  • What is the difference between 'typedef' and 'using'…
  • Difference between 'struct' and 'typedef struct' in C++?
  • problem with client server unix domain stream…
  • Getting infinite loop after entering 2 objects to…
  • Problems Installing CRA & NextJS from NPM…
  • What is and how to fix…
  • 'foo' was not declared in this scope c++
  • Form field border-radius is not working only on the…
  • Adding gif image in an ImageView in android
  • #define macro for debug printing in C?
  • How to remove MySQL completely with config and…
  • How to create ranges and synonym constants in C#?
  • LNK2019 símbolo externo public: bool __thiscall ……
  • Printf width specifier to maintain precision of…
  • typedef struct vs struct definitions
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • GCC: Array type has incomplete element type
  • Why are elementwise additions much faster in…
  • Efficient Algorithm for Bit Reversal (from…
  • polymer 1.0 event firing among nested components
  • Reference — What does this symbol mean in PHP?
  • Program.Mattor(): not all code paths return a value.…
  • Typedef function pointer?
  • Return multiple fields as a record in PostgreSQL…
  • Segmentation Core Dump Problem in Dijkstra Algorithm
  • C++ OpenGL stb_image.h errors
  • How to use html template with vue.js
  • sizeof error : incomplete type is not allowed
  • Casting a void pointer (that is part of a struct)…
  • What does void actually mean? How is it usable in…
  • Converting Oracle SQL Procedure into MySQL Stored Procedure
  • Overloading operators in typedef structs (c++)
  • Knight's tour Problem - storing the valid moves then…
  • Changing Icon Color behind ListTile in an…
  • The static keyword and its various uses in C++
  • Values of member struct get lost after being passed…
  • Undefined reference to 'vtable for ✘✘✘'
  • Draw in Canvas by finger, Android
  • Fastest way to iterate over all the chars in a String
  • How are static members of templated class…
  • Cursor inside LOOP is jumping out too early
  • GetLastInputInfo not returning dwTime
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Objective-C : BOOL vs bool
  • Regex on htaccess file gives INTERNAL REDIRECT error
  • List of ANSI color escape sequences
  • How to filter a RecyclerView with a SearchView
  • Where and why do I have to put the "template" and…
  • How can I set hours and minutes of date with oracle sql?
  • What is the difference between a definition and a…
  • Use of Jquery on scroll event
  • How to convert value of type 'ImagePickerView' to…
  • Docker compose fails to start a service with an…
  • coercing to Unicode: need string or buffer, NoneType…
  • Postgres could not connect to server
  • Check for internet connection with Swift
  • long long int vs. long int vs. int64_t in C++
  • VUE Error when run test unit
  • Implementation of user defined array on stack and/or…
  • How to prevent scrolling the whole page?
  • Why does the C preprocessor interpret the word…
  • What is a typedef enum in Objective-C?
  • CUDA: Pass device function as an argument to global function
  • SwiftUI View Not Updating on Button Toggle After…
  • Why does this core dumped error happen in my class?…
  • C++ Switch statement to assign struct values
  • What does do?
  • How to download and save an image in Android
  • How do I check if a variable is of a certain type…
  • How to properly update subviews on Marionette when…
  • Why should we typedef a struct so often in C?
  • I want to create a SQLite database like in the…
  • What are forward declarations in C++?
  • What's the best way to get the last element of an…
  • Output not incrementing correctly - C++
  • How the int.TryParse actually works
  • how do I replace a static array with a dynamic one?
  • Is gcc's __attribute__((packed)) / #pragma pack unsafe?
  • Accessing a Shared File (UNC) From a Remote,…
  • SVG Mask is "bleeding" on canvas edges
  • Best practice multi language website
  • Auto-fit TextView for Android
  • What does "dereferencing" a pointer mean?
  • Changing PowerShell's default output encoding to UTF-8
  • Efficiency of Java "Double Brace Initialization"?
  • SQL query return data from multiple tables
  • Passing an array by reference in C?
  • C Argument number to create PGM images
  • Renaming column names of a DataFrame in Spark Scala
  • C compile : collect2: error: ld returned 1 exit status
  • What does "Fatal error: Unexpectedly found nil while…
  • Is it possible to print a variable's type in standard C++?
  • Using StringWriter for XML Serialization
  • Getting Layer Feature Information from GeoServer…
  • discord.ext.commands.errors.CommandInvokeError:…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to send FormData objects with Ajax-requests in jQuery?

Next Post:

How to cancel a local git commit

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error