Huzo
Huzo

Reputation: 1692

immutable structure values in C

Let's assume we have this structure:

typedef struct Node{
    int data;
    struct Node *next;
    struct Node *prev;
}node;

and

typedef struct {
    node *front;
    node *rear;
}deque;

Since it is a doubly linked list, I would like to set deque->front->next = NULL and deque->rear->prev = NULL and I dont want these values to be changed no matter what the other functions do. Is such a thing possible in C ? And how would that be? Thanks.

Upvotes: 1

Views: 114

Answers (1)

freim
freim

Reputation: 596

It is not possible in C. If a variable/field is not constant, it can be assigned anything.

It is possible to do that in C++ by defining a 'deque link' class and overloading its assignment function. Something like this:

class DequeLink {
    public:
        DequeLink& operator = (const DequeLink &dl) { /* check value and assign */ }
        DequeLink& operator = (void *p) { /* need this override to accept NULL as arg */ }

    private:
        DequeLink *m_pActualLink;
};

typedef struct {
    int data;
    DequeLink next;
    DequeLink prev;
} Node;

Upvotes: 2

Related Questions