1

Lets say I use an opaque pointer in C for encapsulation:

myStruct.h

typedef struct myStruct* handle;

handle create(int number);
void increment(const handle aStruct);

myStruct.c

#include "myStruct.h"

struct myStruct
{
    int number;
}

handle create(int number)
{
    handle newStruct = malloc(sizeof(struct myStruct));
    newStruct->number = number;
}

void increment(const handle aStruct)
{
    (aStruct->number)++; //Works when typedef'ed despite the const, doesn't work if I use struct myStruct*
}

Why does it compile and the number increments despite the const? Whats even more strange, if I remove the typedef and use struct myStruct* everywhere now the const works and incrementing results in modifying read-only error.

Can sonebody explain why the typedef changes the const behavior?

Asics
  • 858
  • 1
  • 11
  • 20

0 Answers0