Constant Pointer Variables in C ++

Possible duplicate:
What is the difference between const int *, const int * const and int const *?

I know two variations of pointer variables in C ++ .

Say I have

mystruct{ int num; } 

Option 1:

const mystruct* m1; means that the member variables in m1 cannot be changed, for example, m1->num = 2 will result in an error.

Option 2:

mystruct *const m2 = m1; means that once m2 is set as point m1, an error will be generated if you subsequently set m2 =m3 .

However, there seems to be a third variation that I'm not sure about the property:

Option 3:

 mystruct const * m3; 

What does it mean?

+6
source share
3 answers

Option 3 is exactly the same as option 1. const applies to everything that belongs to the left . If there is nothing (the first option), this refers to what is on the right . In addition, you are missing one option.

 const int* pi1; // varyable pointer to constant int int const* pi2; // again - varyable pointer to constant int int* const pi3; // constant pointer to varyable int // you're missign the next int const * const pi4; // constant pointer to constant int 

I personally prefer the second version to the first, as this is what the compiler parses, and when you read the type from right to left, it’s clearer. :) Besides what I did in the comments, it’s intuitive, isn't it?

Oh, yes, all of the above also applies to volatile . Together they are considered cv-qualifiers ( cv = const volatile ).

And as a last point, for future references: Always cdecl.org . As long as you don't mix with C ++ types, you can find out the value of potentially any declaration. Change Interestingly, he chokes on int const i; . I think I will need to investigate whether the variable ordering of cv qualifiers in C ++ has been introduced.

+7
source

See the link. You will find more options there and learn to read. The principle is very simple!

+3
source

Declarations in C ++ consist of two parts:

decl-specifier-seq init-declarator-list;

Description-specifier-seq is a sequence of keywords such as volatile , const , mutable typedef , etc ... and type. The order of these qualifiers does not matter, so you can write:

 int typedef unsigned A; int const B = 1; 

and they match

 typedef unsigned int A; const int B = 1; 

init-declarator-list is a sequence of comma-separated declared objects. Each of these objects gets a spec-specifier-seq type with some modifiers applied to it:

 int typedef *A, B[10], *const C; 

Here A gets the type "pointer to int", B is an array of int, and C is a constant pointer to int.

As you see in your case:

 mystruct const *m2 = m1; 

const is part of the spec-seq definition, so it changes the mystruct as const, not the pointer itself.

+1
source

Source: https://habr.com/ru/post/888379/


All Articles