Bil_Bomba
Bil_Bomba

Reputation: 181

initialise const struct with const pointer

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?

Upvotes: 3

Views: 198

Answers (2)

Simia_Dei
Simia_Dei

Reputation: 76

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.

Upvotes: 1

nh_
nh_

Reputation: 2241

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 ...
}

Upvotes: 2

Related Questions