r/C_Programming • u/Yha_Boiii • Jul 08 '26
Question assign value to a var inside a global struct?
Hi,
I am trying to optimize for memory proximity and need to create a struct with a var inside and with a value already? how would it be done?
mock code:
#include "stdio.h"
struct {
uint32_t OrderID;
uint8_t Order_State_Decition_Branch_Flag = 0b00000000;
} Order_Pipeline_Struct_To_Follow_State;
int main() {
// usage of the struct
}
13
Upvotes
22
u/ByMeno Jul 08 '26
you can assign like this
Edit: you cannot set a default value like in C++ inside a structure
5
u/mykesx Jul 08 '26
I like to use a factory style scheme. Like
struct Order_Pipeline_Struct_To_Follow_State *Create() { ... }
The create function allocates a struct instance, sets the member variables, and returns a pointer to the struct instance created.
Your choices of variable and struct names are painful to read and use. OrderPipeline is clear and succinct enough for the struct name. decitationFlag is clear, too.
I really like CamelCase names. All UPPERCASE for defines and constants, CamelCase for struct names and function names, camelCase for variables. Unimportant variables inside functions can use camel_case style. Visually you can tell what's what.
Others might have their own standard, but I like this best.
4
u/Educational-Paper-75 Jul 08 '26
Functions can return structs, so it's easiest to create an initializing create() function, directly returning an initialized struct with defaults to be assigned to a global struct variable.
2
u/pjl1967 Jul 08 '26
If you're initializing to zero (as your example shows) and a variable of that structure is:
staticdata) is initialized to zero (or equivalent) by default;static) and using C23, then assign= { };static) and using C < C23, then assign= { 0 }.If you want to initialize to a value other than zero, then use designated initializers as someone else suggested, i.e., a
.followed by the member name followed by=value.If you meant initialize a specific member of all instances, then there's no direct way to do that in C. You need to repeat one of the above for all instances or have an
initfunction that does the initialization at run-time.1
u/andrewcooke Jul 08 '26
(only very slightly helpful, sorry, but i guess you probably mean decision (with an s))
1
u/SmokeMuch7356 Jul 08 '26
You can't specify a default value in the type definition; you'd have to initialize each instance when you create it. I'm shortening some of your names; I'm all for using meaningful identifiers, but there's a point where it gets cumbersome.
although it may be better just to write
or