Tag: volatile, mutable, const, C++

  • Explain the Differences Between `volatile`, `mutable`, and `const` Keywords in C++

    The `volatile`, `mutable`, and `const` keywords serve different purposes in C++. `volatile` prevents the compiler from optimizing a variable, as its value may change at any time. `mutable` allows modification of class member variables even in a `const` object. `const` ensures that a variable’s value cannot be changed once initialized.

    Example of `volatile`:

    volatile int counter = 0;

    Example of `mutable`:

    class MyClass { mutable int value; public: void setValue(int v) const { value = v; } };

    Example of `const`:

    const int maxLimit = 100;