Declaring constants in struct

Discussion in 'Programmer's Corner' started by aamirali, Mar 6, 2013.

  1. aamirali

    Thread Starter Member

    Feb 2, 2012
    I have a structure:

    Code ( (Unknown Language)):
    1. typedef struct
    2. {
    3.     int a;
    4.     int b;
    5.     int c;
    7. }my_str;
    I want to make 'c' const & its value to be fixed. How can do it
  2. ErnieM

    AAC Fanatic!

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

    Code ( (Unknown Language)):
    1.    my_str st1 = {0,0,15};   // make st1.c = 15
  3. JohnInTX


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

    For PIC18 using your typedef:

    Code ( (Unknown Language)):
    1. const my_str test = {1,2,3}; puts the initialized struct in ROM, making fixed data
    2. near my_str test = {1,2,3}; puts the initialized struct in ACCESS RAM, initializing it at startup.
    3. my_str test = {1,2,3}; puts struct in general purpose RAM and initializes it
    4. 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: Mar 6, 2013