views:

8154

answers:

7

Hi guys!

I'm not a specialist for ANSI C (or regular C at all), so I stumbled about this stupid thing:

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

typedef struct MY_TYPE {
  boolean 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 ANSI C? Or is there anything better or at least working.

I feel sorry to ask this. %-)

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

A: 

As far as I can remember, this is not correct syntax even in C++. You can use the braces only in the declaration. Afterwards you should initialize it field by field.

Hosam Aly
Damn, this hurts... the struct is about 30 fields with structs inside. Anyways, have to do it that way now.
cringe
+1  A: 
void function(void) {
  MY_TYPE a;
  a.flag = true;
  a.value = 15;
  a.stuff = 0.123;
}
robert
+2  A: 

You've almost got it...

MY_TYPE a = { true,15,0.123 };

Quick search on 'struct initialize c' shows me this

Kieveli
I think this is true for standard C, but not for ANSI C(99?).Also I'm bound to coding rules that won't allow me to do declaration and initialization at once, so I have to split it up and initialize every single subelement.
cringe
Initialization can only happen at the point of declaration. That is what it means to 'initialize'. Otherwise you're allowing an undefined value to be the inital value of your variable / struct, and then assigning a value later.
Kieveli
um... You have coding rules that are deliberately bad? Perhaps you should introduce the guy who wrote them to "Resource Acquisition Is Initialization" (http://en.wikipedia.org/wiki/RAII)
James Curran
Trust me, I really, really, can't change a bit of this rules at this point. It feels horrible to code it. And there are a lot of other rules right out of the 70s, like static code headers with management information like Revision number. Changes for every release, even if the source didn't change...
cringe
+1  A: 

a = (MYTYPE){ true, 15, 0.123 };

would do fine in C99

qrdl
A: 

You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).

CesarB
A: 

malloc & memset or calloc

HTH

plan9assembler
Yeah... this might be another way to go. If only you'd expanded and described how that could be implemented =P
Kieveli
DId I mention that I'm not allowed to malloc? %-)
cringe
+6  A: 

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

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