3
votes

I want to form a struct from const parameters passed to the function. As the parameters are const, i guess the struct has to be const too. However, it does not work with pointers.

The following code compiles (MinGW 4.9.2 32bit)

struct structType_t {
    int b;
};

void func1(const int b) {
    const structType_t s={b};  // invalid conversion from 'const int*' to 'int*' [-fpermissive]

    // do something with s;
}

but with pointers it doesn't:

struct structType_t {
    int* b;
};

void func1(const int* b) {
    const structType_t s={b};  // invalid conversion from 'const int*' to 'int*' [-fpermissive]

    // do something with s;
}

Why does the compiler try to cast away the const here? So how can i use a const pointer to initialise a const structure?

2
structType has int* b not const int* b - Bhargav
const int and int const is the same type, const int* and int* const are different types. - Bo Persson
Even if i change the type of b to const int * const its not compiling. The only solution i found, was a const_cast, which i guess is totaly safe here. But i'd like to know, why i need const_cast with pointers, but not with interger. - Bil_Bomba

2 Answers

2
votes

If you change your struct to hold a const int* you can use it to store the const int* passed to the function, regardless of whether your s is const or not.

struct structType_t {
    const int* b;
};

void func1(const int* b) {
     const structType_t s={b};
     // or 
     structType_t s2={b};

    // do something with s or s2 ...
}
0
votes

In the first case you are creating a copy of an int. Copy of const int does not have to be const so it works. In the second case you are creating copy of a pointer to const int and assigning it to a pointer to an int - this is not allowed and that's why it does not compile.