Home > database >  how to detect if the value of a struct field has changed in C?
how to detect if the value of a struct field has changed in C?

Time:08-02

so lets say I have a function which updates a struct field:

struct person {
    int age;
};

void update_struct (int value) {
    person->age = value;
}

I want to detect whether the value of the struct field has changed in another function.

void another_function () {
    
    if (there is a change in the value of the struct field 'age') {
        // do the following;
    }

}

I am struggling to write an if statement condition for that. Help would be much appreciated.

CodePudding user response:

You can't do this directly, either you keep a flag which you modify when you alter a field or you keep a copy of the struct and memcmp it, just remember that alignment may place some padding in the struct to you must make sure that sizeof(type) == sizeof(field1) sizeof(field2) ....

The latter solution wastes more memory but it has the advantage that it's blindly working unless you have pointers inside your struct.

  • Related