Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure initialization in C++

Code snippeed from Android AOSP code , Sensor.cpp has below code.

struct sensors_module_t HAL_MODULE_INFO_SYM = {
    common: {
        tag: HARDWARE_MODULE_TAG,
        version_major: 1,
        version_minor: 0,
        id: SENSORS_HARDWARE_MODULE_ID,
        name: "LGE Sensor module",
        author: "LG Electronics Inc.",
        methods: &sensors_module_methods,
        dso: NULL,
        reserved: {0}
    },
    get_sensors_list: sensors__get_sensors_list,
};

Now i do not understand here what does : means here? Is it some kind of initialization or something else?

I do not know much about C++. so if any link or resource to understand this things will be appreciated. I could not find much by googling for this.

like image 313
Jeegar Patel Avatar asked Feb 10 '16 07:02

Jeegar Patel


1 Answers

It's a compiler-specific extension, an obsolete form of designated initializer. The gcc implementation is documented here.

In C, you might have:

struct point { int x, y; };
struct point p = { 10, 20 };

With the designated initializer feature, introduced in ISO C99, you can write this as:

struct point { int x, y; };
struct point p = { .x = 10, .y = 20 };

But before C99, gcc introduced a similar feature with a different syntax:

struct point { int x, y; };
struct point p = { x: 10, y: 20 };

gcc, or more precisely g++, supports this in C++ mode as well, but C++ has not adopted C99-style designated initializers.

The gcc manual says that the : version of this feature has been obsolete since gcc 2.5, which was released in 1993, so it definitely should not be used in new code.

Note that if the initial value happens to be a small integer constant, as in your example:

    version_major: 1,
    version_minor: 0,

its easily confused with the syntax for bit fields.

For C the .name = value form is valid and portable, as long as your compiler supports C99 or later. For C++, it's not portable, but you can use the C99 syntax as long as you're using g++ or a compiler like clang that's compatible with it.

like image 143
Keith Thompson Avatar answered Oct 02 '22 15:10

Keith Thompson