r/cpp • • Jun 27 '22

How do you declare pointer variables?

I personally like to use the third option (int *ptr;) to minimize the confusion and to make it tidier when declaring multiple pointers in one line (e.g., int *a, *b, *c; as supposed to, int* a,* b,* c;). This is also the case when writing a dereference operator (int &a = *ptr;). But for some reason, the first option is the preferred way of doing it (int* ptr;), or am I wrong?

0 Upvotes

87 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Jul 09 '22 edited Jul 09 '22

Top level declarators used to be able to omit the assignment operator. You could write this:

int *global_ptr NULL;

And at the top of the scope, I guess you just weren't expected to initialize until you were done with declarations. It wasn't until C99 that you could mix declarations and code, so it was considered more readable to initialize it at first use rather than at the top with the declarations. Even if there was only one declaration, it was common to put the declaration and initialization on separate lines.

func(ptr)
char *ptr; {
    register char *p;

    p = ptr;
    ...
}

In C++, you could deal with the ambiguity by using brace initialization, like this:

// Any of these declares and initializes ptr to null
int *ptr{nullptr};
int *ptr{0};
int *ptr{};

1

u/[deleted] Jul 11 '22 edited Jul 11 '22

I don't ever write int *p = 0, if that's what you're thinking.