This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
In C, why is the asterisk before the variable name, rather than after the type?
What's your preferred pointer declaration style, and why?
In C++, i see pointers put in different ways. for example,
char* ptr
char * ptr
char *ptr
Are the 3 examples above identical? (same goes with the &)
Doesn't matter. (Eg. they are the same.) You could even write char*ptr; without any whitespace.
Beware though with multiple declarations on one line: char* ptr, noptr;. Here, the third syntax comes in clearer: char *ptr, noptr;.
My rule to avoid that confusion: Only one variable per line. Another way to do it right without the possibility to miss a *: typedef the pointer, eg:
typedef char* CharPtr;
CharPtr ptr1, ptr2; // now both are pointer
Though then you need to be aware of other things, like constness, so I stick to my rule mentioned above:
typedef char* CharPtr;
const CharPtr p1; // const char* ?? or char* const ??
CharPtr const p2; // char* const ?? or const char* ??
// Eg.: Can't the pointer or the pointee be changed?
(And all of the above also applies to references &.)
C people tend to prefer char *p, whereas C++ people tend to prefer char* p (at least Bjarne does). The compiler could not care less about whitespace, you could just as well say char * p or char*p.
Many people say that char* p is dangerous because char* p, q is potentially confusing. That is correct in principle, but:
To increase readability, you should not declare multiple names in one declaration, anyway.
And more importantly, in C++, you should generally prefer RAII types over raw pointers.
C++ people emphasize the types, and C people emphasize the usage.
So you see char* x in C++, it is because "the type of x is pointer-to-char". C++ has a strong type system on which the language rests. This is not the case in C.
In C, you declare variables according to what you want to do with them. When you see char *x in C, the thought process is "when you dereference x, you get a char". Another example:
char (*f)(int);
reads "when you dereference f and call it with a int, you get a char", ie. f is a pointer to a function which takes int and returns char.
They all work. char *ptr is often advocated because it makes it clearer what is happening in this case:
char *ptr, var;
This declares a char pointer and a char.
It does not matter. However, C++ people tend to prefer char* ptr, while C people prefer char *ptr. It's all a matter of personal preference.
However, note that char* ptr, noptr declares ptr as a pointer and noptr as a char value.
The potential whitespace surrounding the * and & modifiers in declaration have no effect on the compiled code.
C++ is a free-form language. So, space doesn't really count in this case and all mean the same.
Related
I just learned about function pointers and that to declare one, you must put the * in parentheses with the pointer name to make sure it doesn't return an int *.
Is there a difference between
int *p
and
int (*p)
I tried looking this up with cdecl, but no luck so far. cdecl says it is the same thing, but doesn't provide an explanation. If I declared
short (*p)
Would that be a short pointer or a pointer to a short? Would p have a size of 2 bytes or 4? I know similar questions have been asked, but I've had no luck with them so far.
Would there be a difference between
int *p
and
int (*p)
No. Those are two different ways of writing the same type. The parentheses are not magic here -- they just serve to override precedence, just as with arithmetic operators.
The difference is between
int *p();
(declaration of a function "p" returning int *) and
int (*p)();
(declaration of a pointer to a function returning int). Absent the parentheses around *p, the (empty) parameter list associates more tightly with the name being declared.
If I did:
short (*p)
Would be be a short pointer, or a pointer to a short? And would p be 2 bytes, or 4?
Analogous to int (*p) it declares a pointer to a short. The size of the pointer is implementation-specific, but 4 bytes and 8 bytes are common choices. The pointed-to data is expected to be the size of a short, which is also implementation-specific, but is often 2.
The concept of near vs. far pointers is a compiler vendor specific concept (and rarely occurs outside of some strange embedded systems nowadays; x86 machines dropped it when they moved to 32 bit IIRC). There is not, nor has there every been a concept of a "short pointer" declared using short (meaning a smaller than normal pointer), because C's short already has a meaning. A short* is a normal sized pointer that points to a short sized location, that's all.
Basically, sometype (*p) doesn't mean anything different from sometype *p. Function pointers are declared with somereturntype (*p)(argument, types, go here); without the parens for argument types, it's not a function pointer at all.
#include <iostream>
using namespace std;
int main() {
// your code goes here
short (*p);
short *r;
printf("size - %u- %u",sizeof(p) , sizeof(r));
return 0;
}
returns 4 for both of them.
short (*p)
That would be a pointer to a short. Which in most cases is 2 bytes when it is de-referenced. A pointers size will probably be either 4 or 8 bytes on a modern machine.
s = 5;
short *p = &s;
There is no difference in the context you are using it in.
Parenthesis are used to force operator precedence. If there is no need for parenthesis, such as in initialization, both short *p and short (*p) are equivalent (both are pointers to short values in memory). The actual size of pointers should be uniform (and do not correspond in size to the data members they point to) as they simply store the address of the data member in question.
It is possible that you will need to use parentheses to force precedence if you have pointers to objects. For example:
Object *myObject = new Object();
int myObjectSize = *myObject.size(); // INCORRECT: . operator has higher precedence than *
int myObjectSize = (*myObject).size(); // CORRECT: parentheses force precedence
Of course, in this specific situation, myObject->size() is more commonly used (to avoid using parentheses excessively).
So, in this guide I read that saying
char * terry;
was different from saying
char* terry; //or
char *terry; // FYI: I understand what these two do.
as stated by
"I want to emphasize that the asterisk sign (*) that we use when
declaring a pointer only means that it is a pointer (it is part of its
type compound specifier), and should not be confused with the
dereference operator that we have seen a bit earlier, but which is
also written with an asterisk (*). They are simply two different
things represented with the same sign."
However I do not understand why. Perhaps I took the quote the wrong way, now that I have read it once again, but I am still confused. Can anyone tell me if this is wrong or right and why?
Thank you.
No, all three are exactly the same as far as the parser is concerned. People certainly have their reasons for using each style, but there's not really a "right" way. As an editorial note, I prefer:
char *terry;
What the author of your link is describing is that the * in the declaration is somehow different from the unary * operator used to dereference a pointer:
char *terry = "abcdefg"; // declaration & initialization
*terry = 'x'; // dereference
This potential funny business is actually one of the reasons I prefer the notation I mentioned above - it makes both cases look the same, so there's no room for confusion.
I think all three are the same
Once you have declared a pointer e.g.
int *x;
and later on you want to dereference it you'd use
*x
Textbooks often recommend writing char *terry to remind you that in the statement char *terry, jerry terry is a pointer but jerry is not. Avoids a noobie mistake.
Others write char* terry because they read it as "char-pointer terry." These people probably never declare pointers and non-pointers, or even just two pointers, on the same line. Which is not a bad rule to use.
Otherwise, whitespace almost never matters in C++. Except inside identifiers (variable names, function names) and... can't think of anything else.
I prefer
char *terry;
Just because then if you do something like
char *terry, *jerry, larry;
It's obvious you forgot a pointer.
You may have misread.
char * terry;
char* terry;
char *terry;
Are all the same way to declare a char pointer, named terry.
As for the "right" way, that depends on your coding standard. I personally use char* terry
he is trying to differentiate between the definition char *terry and its usage after the definition e.g. perry = *terry; where perry takes the value of terry rather than the address. As far as compilers are concerned, and others have noted in there answers all three definitions are same. I prefer char *terry, where asterisk(*) hugs the variable.
char* terry; //or
char *terry;
Simply means you are declaring a pointer of char type.
Now terry hold the address location of a character variable, which you have might asked terry to point.
If you print terry, it will print the memory location.
If you dereference terry ( *terry) you will get the character, it is pointing to.
That is what that write up you are mentioning is telling.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What makes more sense - char* string or char *string?
The syntax for pointers has never made sense to me. I noticed that both of these options work for declaring a pointer. Which one should I be using?
The whitespace is insigificant for the C compiler.
The difference matters more if you have multiple declarations on the same line:
int* p1, q1; // p1 is a pointer to int, q1 is an int.
int *p2, *q2; // p2 and q2 are both pointers to ints.
Putting the asterisk near to the variable name may help you to remember this. But it's probably better to just declare each variable on its own line.
It's a question of style, so you should probably use the same style (consistently) as others working on the same code. If it's just you, pick whichever you like.
Personally would argue for int *pointer because int* a, b; means the same as int *a; int b; not int *a; int *b; as one might think, but this is admittedly a fringe case.
The spacing is irrelevant for parsing. There are 3 tokens: int, *, and pointer.
They are equivalent, and a matter of personal preference.
For completeness, I would add that if you're declaring two pointers, you will have to write:
int *a, *b;
If you write int *a,b, you end up with one pointer to int and one int.
From Microsoft's All-In-One Code Framework Coding Standards:
You should put a space between the * character(s) and the type when specifying a pointer type/variable, but there should be no space between the '*' character(s) and the variable. Setting this rule is to be consistent and uniform in code.
You can also use
int * pointer
it just a matter of personal preference. The c++ compiler will know what you mean, just as long as you have the correct syntax.
There is no difference between the two. Use the one that you like more.
They are both equal. Choose the one you like the most, or follow the style guidelines if you are editing existing code.
In Java, we can specify a string as final to declare 'constants'. For example
static final String myConst = "Hello";
Is the correct way to do this in c++ like this?
const char * const myConst = "Hello";
I've always seen people do this:
const char * myConst = "Hello";
But, actually, you can change what that pointer points to. So, why do people not declare the pointer as constant as well? What is the correct way to do it?
const std::string myConst("Hello");
Yes, const char* const is the correct way to declare a C-style string which you will not change.
Or better:
#include <string>
const std::string myConst = "Hello";
const char * myConst = "Hello";
This means the object pointed at cannot change.
char * const myConst = "Hello";
This means the location pointed at by the pointer cannot change, but the object's value can.
const char * const myConst = "Hello";
This means neither may change. In my experience no one remembers this, but it's always available on the net!
Typical, three people answer in the time I write mine!
I don't exactly understand your question. To more or less mimic the final Java keyword, it would be either
const char * const myConst = "Hello";
(if the pointer is not going to change), and/or:
const char * myConst = "Hello";
if the pointer may change afterwards. Finally, note that with the first version, you cannot actually change the pointer itself, because it is constant.
With Diego's edit, yes, that the right way to write it. People typically don't declare the variable const because they don't care whether it will be modified, or, rather, trust that it won't be modified (since they know they don't modify it).
They declare the pointed-to const because a string literal really has const characters, so you really must assign it to a variable that has char const * values.
Technically,
char * const myConst = "Hello";
is the most correct answer, as reassigning the pointer would leave you with a string which probably could not be recovered.
Some implementations allow you to change the characters in "Hello" (even if it's a bad idea), so the first const in
char const * const myConst = "Hello";
Is a great idea. Personally as
char const * myConst = ...;
and
const char * myCount = ...;
are equivalent, I tend to enforce a style guideline that the const always follows the item it modifies. It sometimes reduces misconceptions in the long run.
That said, most people don't know how to use const correctly in C++, so it's either used poorly or not at all. That's because they just use C++ as an improved C compiler.
But, actually, you can change what
that pointer points to. So, why do
people not declare the pointer as
constant as well? What is the correct
way to do it?
Because it's rarely useful, more often than not you would want to have the values on the stack (pointers included) to be non-const. Get Sutter & Alexandrescu "Coding Standards" book, it explains this point.
The real point is that programmers are compeled to declare some pointers at least as const char * to store char arrays between double quotes. Nothing force them (no compiler warning or error) to also make the pointer constant... as people are lazy you can draw your own conclusion. They are probably not even really trying to define a constant, they just want to shut off compiler errors (well, warning in this case).
Keeping that in mind, I would probably go for a different solution anyway:
const char myConst[] = "Hello";
The difference here is that this way I won't decay the original byte array used as string to a pointer, I will still have a byte array that can be used exactly as the original literal.
With it I can do things like sizeof(myConst) and get the same result as with sizeof("Hello"). If I change string to a pointer, sizeof would return the size of a pointer, not the size of the string...
... and obviously when doing things this way changing the pointer becomes meaningless, as there is no pointer to change anymore.
I am trying to learn C++ via some web tutorials. I don't have a compiler available to me, otherwise I would try this out. I'm not sure what is meant by a const pointer. Does that just mean it always points to the same memory address? Why would you ever want to do that? Would the following code be legal?
...
int * const aPointer = new int;
... //do something with aPointer
delete aPointer;
... //do something else, including possibly more 'new' statements
aPointer = new int;
...
A simple way to remember how const works with pointers is to remember that it always applies to whatever is to the left of it, unless it's the left-most keyword, in which case it applies to the right.
Examples:
Pointer to a constant char:
The pointer can be changed to point to something else, but the char it initally points to cannot change value.
const char * p;
Constant pointer to a char:
The pointer cannot be changed to point to anything else, but the char it points to can change value.
char *const p;
Constant pointer to a constant char:
The pointer cannot be changed to point to anything else, and the char it points to cannot change value.
const char *const p;
Const pointer could mean a few different things. I recommend checking out the C++ FAQ Lite on the matter.
You can have:
const int* p;
int* const p;
const int* const p;
All three mean different things. Yes, it's kind of confusing.
In your case, you have the second, which means you have a constant pointer to a non-constant object. That is, you can change the value of the integer via the pointer, but you can't change what the pointer points to. So the code you posted would not be legal.
You can't learn to drive a car just by reading books.
Get yourself a C++ compiler if you want to learn C++. g++ is free of charge, as well as Visual Studio 2008 Express Edition.
As for your question, a const pointer is a zone of memory that is ready only. Example: A class may provide read-only access to an internal buffer.
Note that you also have the const pointer that is also const, aka
const char * const p
In that case, even the value of the pointer cannot be modified.
G'day,
To remember this easily you can use the trick that Scott Meyers describes in his excellent book "Effective C++" (sanitised Amazon link)
You draw a line through the declaration where the asterisk is located.
If the keyword const appears to the left of the line, then you can't change the value of the item that you're pointing to.
If the keyword const appears to the right of the line, then you can't change the pointer to point to another location.
If const appears on both sides, then you can't change the pointer and you can't change the value of what you're pointing to.
BTW That book is excellent, and while not for a beginner, is definitely a way of taking your C++ knowledge to the next level! Highly recommended.
HTH
cheers,
A const pointer means that you can change the value of the variable which is being pointed to, but you can't change where the pointer is pointed. I don't use them often myself, but a common application for const pointers is in defining specific memory segments that you need to address. See this question for more information.
As an aside, you should try to get a compiler on your computer if you can. I've shown myself many times that human brains are poor C++ compilers.
Your code is not legal. You can't assign to aPointer (except using copy-style initialisation, which in fact is not assignment even though it looks like it) if aPointer is declared const like that.
But usually when people say "a const pointer", they mean const int * aPointer, not int * const aPointer as you have in your code. The whole internet will explain the difference at the drop of a hat. As far as I know, the term "const pointer" isn't defined in the standard, so we're free to do this even though it's potentially confusing. "Pointer-to-const" would be an unambiguous description, and a pointer-to-const is much more commonly used than a pointer-which-is-itself-const.
A pointer-which-is-itself-const is used to refer to something, where you won't want the pointer to refer to a different thing at any point in its life. For instance, this is a pointer-which-is-itself-const, because "this object" remains the same object through the execution of a member function. The C++ language has opted not to let you decide part way through that you want to assign some other value to this, to make it refer to some other object. In C++ references often serve that purpose too, since they cannot be "re-seated" to change the referand.
In your code, the pointer cannot move, but the data pointed to can change.
It's legal up to the first delete. A subsequent new would not work because it's an assignment to a constant.
It's relatively unusual to see this, more common is to see where the data pointed to is unchangeable but the pointer can move.
int bar;
int baz;
const int * foo = &bar;
*foo = 4; // illegal
foo = &baz; // legal
having both pointer and value being const is common with strings
const wchar_t * const myString = L"String that will never change.";
Since you're new to C++, for the answer to this question and many other questions you may have or don't know you have, check out the C++ FAQ
I don't have a compiler available to me, otherwise I would try this out
Everyone has a C++ Compiler available to them: http://www.online-compiler.com
There are many others, but this seems to work...
As it has already been pointed out the perhaps most common const pointer is
const char* p;
The variable p can change, but the data p points to is unmodifable.
However, moving the const keyword to the left of the asterisk does not alter the meaning of the declaration:
char const* p;
I prefer the later since it becomes much easier to remember where to place the const keywords when declaring const pointers to const pointers:
char const* const* p;
Again, the variable p can change and the data pointed to is unmodifiable. Furthermore, the data is declared as const pointers meaning that it points to data that cannot be modified.
The more common notation for this type is
const char* const* p;
Placing the const keyword immediately to the left of the asterisk it modifies (or ampersand for reference) makes it easy to create complex types involving the const keyword. For example, a pointer to const pointers:
char const** p;
and a const pointer to pointers:
char* const* p;
Remember to "read" pointer declarations from the right to the left, and don't declare more than one pointer in each statement to avoid a lot of confusion.