简体   繁体   中英

Const pointer to const

I have the following function prototype:

void PerformFusionCycle( StructType const* const a[],
                         StructType2 const* const b,
                         const float32 c,
                         StructType3 * const d,
                         StructType3 * const e)

I want to feed the function with values but I don't understand how to declare and give values to the first parameter. If I declare a variable exactly as the parameter needs to be, I cannot modify it's values, "not a modifiable lvalue" error appears. If I declare a variable so I can modify it's values, then I gen "incompatible types at argument #1" compiler error. How should I do this ?

Thanks !

First; the parameter is read as an array of const pointers to const StructType .

http://cdecl.org/ is a nice place for parsing the rather terse c/c++ declaration syntax.

The following would work:

StructType const * aa[2] = { 0, 0 };
PerformFusionCycle( aa /* rest */ );

Const-correctness with pointer-to-pointers is very confusing in general. However, this function has gone out of hand. It has gone past const-correctness, which is good programming practice, into abusing the const keyword for little or no reason.

StructType const* const a[]

Here you probably just want to make sure that the function cannot modify the pointer-to-pointed-at data. Nothing else makes sense in a function prototype. The array syntax is not helpful either, because it will get adjusted to a pointer anyhow. Replace all of this with const StructType** a .

const float32 c,

Making variables passed by value const is not meaningful. It is a local copy anyway, so who cares if it is modified by the function? Typically this only serves to confuse the programmer. And in my experience, such code is often a pretty certain indication that the original programmer was confused.

Similarly StructType3 * const d is not meaningful either. The pointer itself is passed by value, who cares if the function modifies the local copy?

A call for sanity with const-correctness preserved would look like this:

void PerformFusionCycle( const StructType** a,
                         const StructType2* b,
                         float32 c,
                         StructType3* d,
                         StructType3* e)

The first parameter of the function is a pointer to a (possibly first of several) const pointer(s) to const StructType . So a possible valid argument for a can be constructed as follows:

struct StructType const   orig[3] = { {} ,{} , {} };
struct StructType const * a[] = {
    orig, orig + 1, orig + 2
};

PerformFusionCycle(a, /* Other arguments */);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM