Is int* ptr a valid pointer declaration in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is int* ptr a valid pointer declaration in C++

Heya, I know that it compiles and runs but I want to know whether there are any conventions in C++ that wouldn't allow declaring a pointer like this. As far as I know, this is a fully valid declaration but I'm not 100% sure. Thanks for your answers. Stay Healthy.

25th May 2021, 4:10 PM
Lennart Krauch
Lennart Krauch - avatar
5 Answers
+ 3
Nikhil That is incorrect, isn't it? For both declarations int* a, b; int *a, b; 'a' will be a pointer, but 'b' an integer. You can verify this by attempting to assign "nullptr" to 'b'. If you wanted both to be pointers, you would need to declare them the following way: int *a, *b; where both identifiers now refer to pointers. See for example: https://stackoverflow.com/questions/13618282/declaring-multiple-object-pointers-on-one-line-causes-compiler-error Lennart Krauch Your declaration is of course valid. In a pointer declaration, the asterisk may be placed after the type, inbetween, or before the identifier, and you will find a vast amount of discussions on the net regarding the best place for it.
25th May 2021, 4:35 PM
Shadow
Shadow - avatar
+ 3
Shadow wow :o I was deleting my answer blindly trusting Nikhil but you seems to be agree with what I was thinking to know: you could write: int* ptr; as well as: int *ptr; as much as: int * ptr; or even: int*ptr; number of spaces doesn't matter ^^ if that was your question/doubt... why we often see: int *ptr; is because you could inline many pointer declarations, separated by comma: int *p1, *p2; and that sounds more logical (and readable) than: int* p1,* p2;
25th May 2021, 4:40 PM
visph
visph - avatar
+ 1
Ah thank you didn't know that.
25th May 2021, 4:18 PM
Lennart Krauch
Lennart Krauch - avatar
+ 1
Ty everyone for your answers. I wasn't 100% sure ^^
25th May 2021, 9:34 PM
Lennart Krauch
Lennart Krauch - avatar
0
Yes it is valid. you have to only add an asterisk before the variable name.
25th May 2021, 4:13 PM
Eashan Morajkar
Eashan Morajkar - avatar