pointer to array not compatible to a pointer to 'const' array?

前端 未结 4 898
旧巷少年郎
旧巷少年郎 2021-01-19 07:53

In a C module (aka, compilation unit), I want to have some private data, but expose it read-only to the outside world. I achieve that by having a field in a s

4条回答
  •  心在旅途
    2021-01-19 08:23

    I am not entirely sure if this could be considered a good idea, but something that I do sometimes when I'm feeling lazy is to define a "const cast" macro like:

    #define CC(_VAR) ((const typeof(_VAR))(_VAR))
    

    This of course assumes that you have a compiler that supports the typeof extension. Using this (dubious) construction you could then write

    const shape *fooshapes(const foo *f)
    {
        return CC(f->shapes);
    }
    

    Otherwise, C doesn't generally cast to const implicitly. You do have to explicitly cast pointers to const pointers.

提交回复
热议问题