Can you make a variable constant?

I have a variable in a struct and an initialization routine to set everything up in the structure and get it ready for use by the rest of the program. I have two variables in the structure that I don't want to change. Can I make them constant?

I thought of a possible solution: use a pointer to each of the variables and define them as constants in the structure. Something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

struct my_struct {
    const unsigned int my_constant;
    unsigned int my_variable;
};

struct my_struct init_my_struct(void) {
    struct my_struct stMy_struct;

    memset(&stMy_struct, 0, sizeof(stMy_struct));

    unsigned int* temp = &(stMy_struct.my_constant);

    *temp = 52;

    return stMy_struct;
}

int main(void) {
    struct my_struct stMy_struct = init_my_struct();
    printf("my_constant: %d\n", stMy_struct.my_constant);
    
    return 0;
}


It certainly works; but I get this warning from gcc:
 warning: initialisation discards qualifiers from pointer target type

(obviously stating that it is not legal to do this), so I won't be able to compile with -Werror.

It's a pretty ugly method; is there a better one? I guess I don't really need it to be constant, but I'd rather it didn't get changed: it could screw everything else up if I acted as though it's value was 4 and it was really 8 or something like that. I'd also rather not waste time checking (in all of seven functions that depend on that struct) with if statements what the value is, also; then I may aswell hardcode the value anyway.

Edit: I can remove that warning with a cast; but I'd still rather find a less ugly method.
Last edited on
Seems very long winded.
1
2
3
4
5
6
7
struct my_struct init_my_struct(void) 
{
  struct my_struct stMy_struct = {52,0};
    
  return stMy_struct;

}

You can do that?
Why did no-one tell me???

Thank you :)

Use this Code... u did a mistake at line 15 that should be at line 12.

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
struct my_struct {
const unsigned int my_constant;
unsigned int my_variable;
};

struct my_struct init_my_struct(void) {
struct my_struct stMy_struct;
unsigned int* temp = &stMy_struct.my_constant;

memset(&stMy_struct, 0, sizeof(stMy_struct));

*temp = 52;

return stMy_struct;
}

int main(void) {
struct my_struct stMy_struct = init_my_struct();
printf("my_constant: %d\n", stMy_struct.my_constant);

return 0;
}
This again? Seriously, what's with all the const casting questions?

http://www.cplusplus.com/forum/general/17155/

Didn't the term "variable constant" strike you as oxymoronic when you wrote the title?
Last edited on
To princebhavik - You are incorrect.
I always liked Pascal's "variable constants".
Topic archived. No new replies allowed.