Creating a constant instance of a custom data structure

Viewed 102

I've defined those two data structures as types:

typedef struct {
    float x,y,z;
} location3d;

typedef struct {
    location3d location;
    float radius; 
} particle3d;

My question is: can I create a constant location3d or a constant particle3d? I searched about constants but all I found is how to define constant integers or chars... etc.

2 Answers

You use const with user-defined types exactly the same way as with built-in types. And as with other constants, you need to initialize it.

const particle3d my_particle = { {10.0, 21.5, 3}, 1.23};

You can also use designated initializers.

const particle3d my_particle = {.radius = 1.23, .location = {.x = 10.0, .y = 21.5, .z = 3}};

You can use const the same way as with the built-in types.

Have a look at the following implementation:

#include <stdio.h>

typedef struct {
    float x,y,z;
} location3d;

typedef struct {
    location3d location;
    float radius; 
} particle3d;

int main(){

    const particle3d particle = {{1, 2, 3}, 8.9};
    
    printf("%f %f %f\n", particle.location.x, particle.location.y, particle.location.z);

    printf("%f\n", particle.radius);
    
    return 0;
}

Output:

1.000000 2.000000 3.000000
8.900000

PS: Author recently removed the C++ tag. Removed C++ code and shifted to C.

Related