What is the difference between the ways of declaring a pointer? [duplicate]
What changes between these two ways?
int *ptr
and int* ptr
Both work the same way, but for my code or performance my program has difference?
#include <iostream>
using namespace std;
int main() {
int a(5);
int *ptr1 = &a;
int* ptr2 = &a;
cout << "a: (0x" << hex << uppercase << (uintptr_t)&a << ") = " << dec << a << endl;
cout << "ptr1: (0x" << hex << uppercase << (uintptr_t)ptr1 << ") = " << dec << *ptr1 << endl;
cout << "ptr2: (0x" << hex << uppercase << (uintptr_t)ptr2 << ") = " << dec << *ptr2 << endl;
return 0;
}
Output:
a: (0x61FE0C) = 5
ptr1: (0x61FE0C) = 5
ptr2: (0x61FE0C) = 5
Absolutely nothing. Whitespace is ignored.
Where to align is a decision of style, based on team conventions and rules (if any) or personal preference, and is mostly to improve the readability of the code. It doesn't change how the code is compiled.
They're the same:
int a {5};
int *ptr1 = &a; // same as below
int* ptr2 = &a;
Not just for pointers but also for references:
int a {5};
int& b = a;
int &c = b; // same as above
int & d = a; // same
The both declarations have the same meaning. You could consider even two more declarations
int *ptr1 = &a;
int* ptr2 = &a;
int * ptr3 = &a;
int*ptr4 = &a;
or
int*ptr4=&a;
The compiler can parse these records correctly without an ambiguity. The symbol *
may be a part neither of an identifier nor of a keyword.
The difference between the records of these two declarations
int *ptr1 = &a;
int* ptr2 = &a;
lies in the semantic between declarators and type specifiers.
For example you may write
int ( *ptr ) = &a;
but you may not write
( int * ) ptr = &a;
Or you may write
int typedef *ptr;
but you may not write
int * typedef ptr;
So it is preferable to write
int *ptr1 = &a;
instead of
int* ptr2 = &a;
For example this declaration
int* ptrq, ptr2;
does not declare two pointers. Instead you need to write
int *ptr1, *ptr2;
Or if you have a pointer to an array like
int a[10];
then you even can not use the combination int*
. You have to write
int ( *ptr )[10] = &a;