포인터 선언에 별표 배치
나는 최근에 마침내 C / C ++를 배워야한다고 결정했고, 포인터에 대해 정말로 이해하지 못하는 것이 한 가지 있습니다. 더 정확하게는 그 정의입니다.
이 예는 어떻습니까?
int* test;
int *test;
int * test;
int* test,test2;
int *test,test2;
int * test,test2;
이제 내 이해에 따르면 처음 세 가지 경우는 모두 동일합니다. 테스트는 정수가 아니라 하나에 대한 포인터입니다.
두 번째 예제 세트는 좀 더 까다 롭습니다. 경우 4에서 test와 test2는 모두 int에 대한 포인터가되고, 경우 5에서는 test 만 포인터 인 반면 test2는 "실제"int입니다. 사례 6은 어떻습니까? 사례 5와 같습니까?
4, 5, 6은 동일하며 테스트 만 포인터입니다. 두 개의 포인터를 원하면 다음을 사용해야합니다.
int *test, *test2;
또는 더 나은 (모든 것을 명확하게하기 위해) :
int* test;
int* test2;
별표 주위의 공백은 의미가 없습니다. 세 가지 모두 같은 의미입니다.
int* test;
int *test;
int * test;
" int *var1, var2
"는 사람들을 혼란스럽게하기위한 사악한 구문이므로 피해야합니다. 다음으로 확장됩니다.
int *var1;
int var2;
"Clockwise Spiral Rule" 을 사용하면 C / C ++ 선언을 구문 분석하는 데 도움이됩니다.
따라야 할 간단한 세 단계가 있습니다.
알 수없는 요소부터 시작하여 나선 / 시계 방향으로 이동합니다. 다음 요소가 발견되면 해당 영어 문으로 대체하십시오.
[X]
또는[]
: 배열 X 크기 ... 또는 배열 정의되지 않은 크기 ...
(type1, type2)
: 함수 전달 type1 및 type2 반환 ...
*
: 포인터 ...- 모든 토큰이 덮일 때까지 나선형 / 시계 방향으로 계속하십시오.
- 항상 괄호 안의 모든 것을 먼저 해결하십시오!
또한 선언은 가능한 경우 별도의 문으로 작성해야합니다 (대부분의 경우 사실임).
많은 코딩 지침 은 한 줄에 하나의 변수 만 선언하도록 권장합니다 . 이렇게하면이 질문을하기 전에 가졌던 종류의 혼동을 피할 수 있습니다. 내가 함께 일한 대부분의 C ++ 프로그래머는 이것에 집착하는 것 같습니다.
내가 아는 약간의 제쳐두고 유용한 것은 선언을 거꾸로 읽는 것입니다.
int* test; // test is a pointer to an int
이것은 매우 잘 작동하기 시작합니다. 특히 여러분이 const 포인터를 선언하기 시작할 때 그것이 const 인 포인터인지 아니면 포인터가 가리키는 것이 const인지를 아는 것이 까다로워집니다.
int* const test; // test is a const pointer to an int
int const * test; // test is a pointer to a const int ... but many people write this as
const int * test; // test is a pointer to an int that's const
다른 사람들이 언급했듯이 4, 5 및 6은 동일합니다. 종종 사람들은이 예제를 사용 *
하여 유형이 아닌 변수에 속하는 인수를 만듭니다 . 스타일의 문제이긴하지만 이렇게 생각하고 작성해야하는지에 대한 논쟁이 있습니다.
int* x; // "x is a pointer to int"
or this way:
int *x; // "*x is an int"
FWIW I'm in the first camp, but the reason others make the argument for the second form is that it (mostly) solves this particular problem:
int* x,y; // "x is a pointer to int, y is an int"
which is potentially misleading; instead you would write either
int *x,y; // it's a little clearer what is going on here
or if you really want two pointers,
int *x, *y; // two pointers
Personally, I say keep it to one variable per line, then it doesn't matter which style you prefer.
#include <type_traits>
std::add_pointer<int>::type test, test2;
In 4, 5 and 6, test
is always a pointer and test2
is not a pointer. White space is (almost) never significant in C++.
In my opinion, it is better to put the asterisk next to the pointer name, rather than the type. Compare e.g.:
int *pointer1, *pointer2; // Fully consistent, two pointers
int* pointer1, pointer2; // Inconsistent -- because only the first one is a pointer, the second one is an int variable
// The second case is unexpected, and thus prone to errors
Why is the second case inconsistent? Because e.g. int x,y;
declares two variables of the same type but the type is mentioned only once in the declaration. This creates a precedent and expected behavior. And int* pointer1, pointer2;
is inconsistent with that because it declares pointer1
as a pointer, but pointer2
is an integer variable. Clearly prone to errors and, thus, should be avoided (by putting the asterisk next to the pointer name, rather than the type).
However, there are some exceptions where you might not be able to put the asterisk next to an object name (and where it matters where you put it) without getting undesired outcome — for example:
MyClass * volatile MyObjName
The pointer is a modifier to the type. It's best to read them right to left in order to better understand how the asterisk modifies the type. 'int *' can be read as "pointer to int'. In multiple declarations you must specify that each variable is a pointer or it will be created as a standard variable.
1,2 and 3) Test is of type (int *). Whitespace doesn't matter.
4,5 and 6) Test is of type (int *). Test2 is of type int. Again whitespace is inconsequential.
You can think of 4, 5, and 6 as follows: declaring the type only has to be done once, but if you want to declare a pointer to that type (by adding an asterisk) you have to do so for each variable.
When declaring a pointer variable, I always add whitespace between the variable and asterisk, even if I'm declaring more than one in a line. Not doing so makes me confuse it for a dereferencing expression nearly every time.
The rationale in C is that you declare the variables the way you use them. For example
char *a[100];
says that *a[42]
will be a char
. And a[42]
a char pointer. And thus a
is an array of char pointers.
This because the original compiler writers wanted to use the same parser for expressions and declarations. (Not a very sensible reason for a langage design choice)
I would say that the initial convention was to put the star on the pointer name side (right side of the declaration
in the c programming language by Dennis M. Ritchie the stars are on the right side of the declaration.
by looking at the linux source code at https://github.com/torvalds/linux/blob/master/init/main.c we can see that the star is also on the right side.
You can follow the same rules, but it's not a big deal if you put stars on the type side. Remember that consistency is important, so always but the star on the same side regardless of which side you have choose.
Cases 1, 2 and 3 are the same, they declare pointers to int variables. Cases 3, 4 and 5 are the same, as they declare one pointer to, and one int variable respectively. If you want do declare two pointers in one line (which you shouldn't), you need to put an asterisk in front of each variable name:
int *test, *test2;
There is no certain correct way that says where the asterisk goes. int* test
looks better because it is easier for us to imagine that appending *
to the end of a type means "pointer to" that type. However, int *test
makes more sense, because you can work with it like the minus sign in maths:
-(-x) = x
is analogous to
*(*test) = test
This has always helped me. Sadly, the upshot of it all is that sometimes I use int* test
and sometimes int *test
.
A good rule of thumb, a lot of people seem to grasp these concepts by: In C++ a lot of semantic meaning is derived by the left-binding of keywords or identifiers.
Take for example:
int const bla;
The const applies to the "int" word. The same is with pointers' asterisks, they apply to the keyword left of them. And the actual variable name? Yup, that's declared by what's left of it.
참고URL : https://stackoverflow.com/questions/180401/placement-of-the-asterisk-in-pointer-declarations
'program story' 카테고리의 다른 글
이드의 의미는 무엇입니까? (0) | 2020.09.16 |
---|---|
단일 행 중첩 For 루프 (0) | 2020.09.16 |
서버에서 SSL을 사용할 수 없습니다. (0) | 2020.09.15 |
디렉토리가 있는지 확인하고 하나의 명령으로 삭제하십시오. (0) | 2020.09.15 |
내 Android debug.keystore 비밀번호가 기억 나지 않습니다. (0) | 2020.09.15 |