Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising C structures in C++ code

Is there a better way to initialise C structures in C++ code?

I can use initialiser lists at the variable declaration point; however, this isn't that useful if all arguments are not known at compile time, or if I'm not declaring a local/global instance, eg:

Legacy C code which declares the struct, and also has API's using it

typedef struct
{
    int x, y, z;
} MyStruct;

C++ code using the C library

void doSomething(std::vector<MyStruct> &items)
{
    items.push_back(MyStruct(5,rand()%100,items.size()));//doesn't work because there is no such constructor
    items.push_back({5,rand()%100,items.size()});//not allowed either

    //works, but much more to write...
    MyStruct v;
    v.x = 5;
    v.y = rand()%100;
    v.z = items.size();
    items.push_back(v);
}

Creating local instances and then setting each member one at a time (myStruct.x = 5; etc) is a real pain, and somewhat hard to read when trying to add say 20 different items to the container...

like image 978
Fire Lancer Avatar asked Jan 03 '10 12:01

Fire Lancer


People also ask

How do you initialize a structure in C?

Structure members can be initialized using curly braces '{}'.

How do you initialize a structure?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

What is initializing in C?

Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.

Can you initialize values in a struct?

No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).


1 Answers

If you can't add a constructor (which is the best solution in C++03 but you probably have compatibility constraint with C), you can write a function with the same effect:

MyStruct makeAMyStruct(int x, int y, int z)
{
    MyStruct result = { x, y, z };
    return result;
}

items.push_back(makeAMyStruct(5,rand()%100,items.size()));

Edit: I'd have checked now that C++0X offers something for this precise problem:

items.push_back(MyStruct{5,rand()%100,items.size()});

which is available in g++ 4.4.

like image 97
AProgrammer Avatar answered Oct 12 '22 10:10

AProgrammer