3

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?

3
  • structType has int* b not const int* b Commented Nov 17, 2015 at 14:38
  • const int and int const is the same type, const int* and int* const are different types. Commented Nov 17, 2015 at 14:42
  • 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. Commented Nov 17, 2015 at 15:20

2 Answers 2

2

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 ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

I can not change the struct to hold a const. However, declaring a struct as const is making all the members const, right?
Yes, it will make it hold a const pointer to an int (int* const) but not a pointer to a const int (const int*), which is what you want to store.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.