Is there any good way to do it

Discussion in 'C Programming' started by qianz99, Oct 12, 2005.

  1. qianz99

    qianz99 Guest

    Hello I am writing a big program.

    I have define a struction

    typedef struct
    int Name;
    int Year;

    Now I'd like to define a sequence of A, such as

    Birth A = {1,1990}
    Birth B = {1,1991}

    I hope to use #define so that A,B can be used as constant.
    Can I?
    and is it a good way of programming?

    qianz99, Oct 12, 2005
    1. Advertisements

  2. birth A = {1,1990};
    birth B = {1,1991};

    :I hope to use #define so that A,B can be used as constant.
    :Can I?


    What you can do is

    #define B90 {1,1990}
    #define B91 {1,1991}

    birth A = B90;
    birth B = B91;

    and use B90 or B91 wherever else in the code that you happen to need
    to initialize new variables to those values.

    But A and B will be writable. You cannot create an unwritable structure
    with any particular contents: the closest you can get is, as in the
    above, to define textual substituations that happen to expand to the
    values you need.

    You could also get fancier with functions that return const pointers
    to structures. You could probably even have something like

    const birth B90(void) { birth B90_temp = {1,1990}; return B90_temp; }

    but returning whole structures tends to make old-time programmers
    Walter Roberson, Oct 12, 2005
    1. Advertisements

  3. Right, the {1,1990} construct can be used in an initializer, but it
    can't be used as an expression. C99 has compound literals, but
    they're not universally supported yet.
    Of course you can:

    const birth A = { 1, 1990 };
    const birth B = { 2, 1991 };

    A and B aren't true "constants"; they're best thought of as read-only
    variables. But they're probably suitable for the OP's purposes.
    Keith Thompson, Oct 12, 2005
  4. qianz99

    tanmoy87544 Guest

    The answer is correct for C89
    Actually, you can define const objects. Except for odd uses of strchr
    etc. or by use of casts, attempts to write to them always involves a
    constraint violation; in the exceptional cases, it invokes undefined
    behaviour. So, they are kind of unwritable.
    A definition of a function type which is incompatible with birth(void),
    but which is functionally identical.
    But using qualified values in C rather than qualified objects just to
    make someone queasy!
    tanmoy87544, Oct 13, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.