Declaring constants in struct

Thread Starter

aamirali

Joined Feb 2, 2012
412
I have a structure:

Rich (BB code):
typedef struct
{
    int a;
    int b;
    int c;

}my_str;
I want to make 'c' const & its value to be fixed. How can do it
 

ErnieM

Joined Apr 24, 2011
8,377
About the only way it to initialize the value when you declare each instance of the struct, then never change that value.

Rich (BB code):
   my_str st1 = {0,0,15};   // make st1.c = 15
 

JohnInTX

Joined Jun 26, 2012
4,787
Most C compilers for embedded systems (PIC18 for example) support specifying where to store things.

For PIC18 using your typedef:

Rich (BB code):
const my_str test = {1,2,3}; puts the initialized struct in ROM, making fixed data
near my_str test = {1,2,3}; puts the initialized struct in ACCESS RAM, initializing it at startup.
my_str test = {1,2,3}; puts struct in general purpose RAM and initializes it
my_str test; allocates space in GP RAM and initializes it to all 0.
Compilers for other chips will have similar functions with some differences that reflect the underlying hardware.

If portability is a concern, hardware-specific keywords should be #defined with something generic e.g.
#define const inROM

and declare the struct as
inROM my_str test = {1,2,3};
 
Last edited:
Top