What is the difference between these declarations in C?

后端 未结 2 1395
一整个雨季
一整个雨季 2021-01-01 03:14

In C and C++ what do the following declarations do?

const int * i;
int * const i;
const volatile int ip;
const int *i;

Are any of the above

相关标签:
2条回答
  • 2021-01-01 03:51

    const int * i;

    i is a pointer to constant integer. i can be changed to point to a different value, but the value being pointed to by i can not be changed.

    int * const i;

    i is a constant pointer to a non-constant integer. The value pointed to by i can be changed, but i cannot be changed to point to a different value.

    const volatile int ip;

    This one is kind of tricky. The fact that ip is const means that the compiler will not let you change the value of ip. However, it could still be modified in theory, e.g. by taking its address and using the const_cast operator. This is very dangerous and not a good idea, but it is allowed. The volatile qualifier indicates that any time ip is accessed, it should always be reloaded from memory, i.e. it should NOT be cached in a register. This prevents the compiler from making certain optimizations. You want to use the volatile qualifier when you have a variable which might be modified by another thread, or if you're using memory-mapped I/O, or other similar situations which could cause behavior the compiler might not be expecting. Using const and volatile on the same variable is rather unusual (but legal) -- you'll usually see one but not the other.

    const int *i;

    This is the same as the first declaration.

    0 讨论(0)
  • 2021-01-01 03:56

    You read variables declarations in C/C++ right-to-left, so to speak.

    const int *i;  // pointer to a constant int (the integer value doesn't change)
    
    int *const i;  // constant pointer to an int (what i points to doesn't change)
    
    const volatile int ip;  // a constant integer whose value will never be cached by the system
    

    They each have their own purposes. Any C++ textbook or half decent resource will have explanations of each.

    0 讨论(0)
提交回复
热议问题