C++ Pointer in Function - c++

I know that technically all three ways below are valid, but is there any logical reason to do it one way or the other? I mean, lots of things in c++ are "technically valid" but that doesn't make them any less foolish.
int* someFunction(int* input)
{
// code
}
or
int *someFunction(int *input)
{
// code
}
or
int * someFunction(int * input)
{
// code
}
I personally think the third one is annoying, but is there a "correct" way? I am typically more inclined to use the first one (as the second looks more like it's being used as the dereference operator - which it isn't)

It's a question of personal taste. I prefer the 1st approach, whereas the old-school programmers tend to use the 2nd (coming from the old good C times).
For a difference, consider the following:
int* p, q; // here p is a pointer to int, but q is just an int!
The attractiveness of the first way (int* p) is that it reads as "int pointer is a type of p", whereas the alternate int *p reads as "int is a type of *p" (which is also correct).

All are equivalent. Choose the flavor that suits you best. Just be sure whichever you chose, you apply that choice in every case. Where your stars and curly braces go is far less important than putting them in the same place every time.
Personally, I prefer int* someFunction(int* input);, but who cares?

I personally use the second option, because int *p1, p2; is better looking and less confusing than int* p1, p2; or int * p1, p2;. The same with functions' return type to keep the same style.
It's a personal thing, there isn't any 'good' or 'bad' way.

All are equivalent. I like the third because it makes the * stand out. Other people differ.
If you're working on a project with others, use the established style. If not, decide on your own style.

There's no "one correct way". It is all a matter of personal preference.
The first approach is not generally compatible with having multiple declarators in one declaration, so people who use it usually don't use more than one declarator in a declaration
int* p, b; // misleading, since `b` is `int` and not `int*`
Yet the first approach has its supporters.

I prefer the second, for the reasons explained in my previous answer. *someFunction(someInput) has type int.
EDIT: Kernigan and Ritchie definitely intended the second. See for instance this snippet from the white bible.

Related

About keyword “const” in c++

According to the c++ grammar, const int* const p means that what p points to and it' value can't be rewritten.But today I found that if I code like this:
void f(const int* const p)
{
char* ch = (char*) p;
int* q = (int*) ch;
(*q) = 3; //I can modify the integer that p points to
}
In this condition,the keyword "const" will lose it's effect.Is there any significance to use "const"?
You are casting away the constness here:
char* ch = (char*) p;
Effectively, you are saying "I know what I am doing, forget you are const, I accept the consequences." C++ allows you to do stuff like this because sometimes it can be useful/necessary. But it is fraught with danger.
Note that if the argument passed to the function were really const, then your code would result in undefined behaviour (UB). And you have no way of knowing from inside the function.
Note also that in C++ it is preferable to make your intent clear,
int* pi = const_cast<int*>(p);
This makes it clear that your intention is to cast away the const. It is also easier to search for. The same caveats about danger and UB apply.
Your example will crash the app if const int* const p points to a compile time constant, when casting away constancy you need to be sure what you are doing.
C++ is a language for adults, extra power will never be sacrificed for ephemeral safety, it is the code author's choice whether to stay in a safe zone or to use cast operators and move one step closer to C/asm.
C/C++ will let you do many things that allow you to 'hurt' yourself. Here, casting away the const of p is "legal" because the compiler assumes you know what you are doing. Whether this is good coding style or not is another matter.
When you do something like this, you assume responsibility for any side effects and issues it could create. Here, if the memory pointed to in the parameter is static memory, the program will likely crash.
In short, just because you can do something doesn't mean it is a good idea.
The const keyword is a way to use the compiler to catch programming mistakes, nothing more. It makes no claims about the mutability of memory at runtime, only that the compiler should shout at you if you directly modify the value (without using C-style casts).
A C-style cast is pretty much a marker saying 'I know what I'm doing here'. Which in most instances is false.
Here you change the type of the pointer. Using such a cast (C-type) cast you can change it to any possible pointer with no problem.
The same way you can use c++ cast: const_cast<...>(...):
int* p_non_const = const_cast<int*>(p);
In this case (I hope) you see immediately what is happening - you simply rid of the constness.
Note that in your program you also don't need temprorary variable ch. You can do it directly:
int* q = (int*) p;
In principle you should not use such a cast, because correctly designed and written program doesn't need it. Usually the const_cast is used for quick and temporary changes in the program (to check something) or to use a function from some unproperly designed library.

Is there a difference between int *x and int* x in C++? [duplicate]

This question already has an answer here:
Difference between char* var; and char *var;? [duplicate]
(1 answer)
Closed 9 years ago.
I'm getting back into my C++ studies, and really trying to understand the basics. Pointers have always given me trouble, and I want to make sure I really get it before I carry on and get confused down the road.
Sadly, I've been stymied at the very outset by an inconsistency in the tutorials I'm reading. Some do pointer declarations this way:
int *x
and some do it this way:
int* x
Now the former of the two seems to be by far the most common. Which is upsetting, because the second makes much more sense to me. When I read int *x, I read "Here is an int, and its name is *x", which isn't quite right. But when I read the second, I see "here is an int pointer, and its name is x", which is pretty accurate.
So, before I build my own mental map, is there a functional difference between the two? Am I going to be a leper outcast if I do it the second way?
Thanks.
The famous Bjarne Stroustrup, notable for the creation and the development of the C++, said ...
The choice between "int* p;" and "int *p;" is not about right and
wrong, but about style and emphasis. C emphasized expressions;
declarations were often considered little more than a necessary evil.
C++, on the other hand, has a heavy emphasis on types.
A "typical C programmer" writes "int *p;" and explains it "*p is what
is the int" emphasizing syntax, and may point to the C (and C++)
declaration grammar to argue for the correctness of the style. Indeed,
the * binds to the name p in the grammar.
A "typical C++ programmer" writes "int* p;" and explains it "p is a
pointer to an int" emphasizing type. Indeed the type of p is int*. I
clearly prefer that emphasis and see it as important for using the
more advanced parts of C++ well.
So, there's no difference. It is just a code style.
From here
To the compiler, they have exactly the same meaning.
Stylistically, there are arguments for and against both.
One argument is that the first version is preferable because the second version:
int* x, y, z;
implies that x, y and z are all pointers, which they are not (only x is).
The first version does not have this problem:
int *x, y, z;
In other words, since the * binds to the variable name and not the type, it makes sense to place it right next to the variable name.
The counter-argument is that one shouldn't mix pointer and non-pointer type in the same declaration. If you don't, the above argument doesn't apply and it makes sense to place the * right next to int because it's part of the type.
Whichever school of thought you decide to subscribe to, you'll encounter both styles in the wild, and more (some people write int * x).
No difference at all.
It is just a matter of style.
I personally prefer this:
int *x;
over this,
int* x;
Because the latter is less readable when you declare many variables on the same line. For example, see this:
int* x, y, z;
Here x is a pointer to int, but are y and z pointers too? It looks like they're pointers, but they are not.
There is no difference. I use the int* x form because I prefer to keep all of the type grouped together away from the name, but that kind of falls apart with more complex types like int (*x)[10].
Some people prefer int *x because you can read it as "dereferencing x gives you an int". But even that falls apart when you start to use reference types; int &x does not mean that taking the address of x will give you an int.
Another reason that you might prefer int *x is because, in terms of the grammar, the int is the declaration specifier sequence and the *x is the declarator. They are two separate parts of the declaration. This becomes more obvious when you have multiple declarators like int *x, y;. It might be easier to see that y is not a pointer in this case.
However, many people, like myself, prefer not to declare multiple variables in a single declaration; there isn't exactly much need to in C++. That might be another reason for preferring the int* x form.
There's only one rule: be consistent.
There's absolutely no difference.
No difference. I've tended to prefer the
int* x
Due to thinking of 'x' as having type int* .
To the compiler they are the same
But at the same time the difference is readabilty when there are multiple variables
int *x,y
However this is more misleading
int* x,y
Both are the same thing.
The former is although preferred. Suppose you want to declare 2 pointers p & q in the same line.
int* p, q;
This actually means 'p' is a pointer to an int, while 'q' is an int.
The correct syntax would be:
int* p, *q;
Hence, we include the * in the pointer's name.
This is a type of style of coding. There's no difference, just a matter of preference as you said yourself.Hope you clear.Enjoy coding
In my opinion, in the expression int * x,y; x and y are names of variables. When these names are declared like this by programmer, it means they have same type and int * is the
type.

int* pointer vs. int *pointer for pointer declaration [duplicate]

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.

C++ reference syntax

Which is the correct way to specify a reference. I know both works with the compiler, but wanted to know the correct way since I have seen both in code bases.
void Subroutine(int &Parameter)
{
Parameter=100;
}
OR
void Subroutine(int& Parameter)
{
Parameter=100;
}
There is no 'correct' way, in the same way like there is no 'correct' way to place your parentheses and brackets. It's a matter of style and preference.
It's more important to be consistent.
When it comes to pointers, C programmers tend to write int *i which reads "evaluating *i yields an int". This is not possible with references. If you write int &i, evaluating &i does not yield an int, but rather a pointer to an int, because & has different meanings in declarations and expressions.
That's why I prefer to declare reference variables as int& i, because i is a reference to an int.
It's a matter of preference, both are correct, personally I nowadays like to write it as type&
I think the two are functionally identical. I personally prefer int& Parameter since it makes more sense to me -- i.e. a variable named Parameter is of type reference-to-int, whereas int &Parameter doesn't immediately make that connection to me. Most examples I've seen use the int& form as well. (i.e. see http://www.cprogramming.com/tutorial/references.html).
That's code style issue, no one is good or bad, correct or wrong.
I use this:
int & a;
int * b;
Too many spaces (any maybe a little confusing with binary operator & and *) but it looks clear to me.
As long as consistent, whatever your style is correct.

Needless pointer-casts in C

I got a comment to my answer on this thread:
Malloc inside a function call appears to be getting freed on return?
In short I had code like this:
int * somefunc (void)
{
int * temp = (int*) malloc (sizeof (int));
temp[0] = 0;
return temp;
}
I got this comment:
Can I just say, please don't cast the
return value of malloc? It is not
required and can hide errors.
I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.
However, I wonder how casts like this can hide errors. Any ideas?
Edit:
Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.
It seems fitting I post an answer, since I left the comment :P
Basically, if you forget to include stdlib.h the compiler will assume malloc returns an int. Without casting, you will get a warning. With casting you won't.
So by casting you get nothing, and run the risk of suppressing legitimate warnings.
Much is written about this, a quick google search will turn up more detailed explanations.
edit
It has been argued that
TYPE * p;
p = (TYPE *)malloc(n*sizeof(TYPE));
makes it obvious when you accidentally don't allocate enough memory because say, you thought p was TYPe not TYPE, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings.
I would like to point out 2 things:
you should write p = malloc(sizeof(*p)*n); to always ensure you malloc the right amount of space
with the above approach, you need to make changes in 3 places if you ever change the type of p: once in the declaration, once in the malloc, and once in the cast.
In short, I still personally believe there is no need for casting the return value of malloc and it is certainly not best practice.
This question is tagged both for C and C++, so it has at least two answers, IMHO:
C
Ahem... Do whatever you want.
I believe the reason given above "If you don't include "stdlib" then you won't get a warning" is not a valid one because one should not rely on this kind of hacks to not forget to include an header.
The real reason that could make you not write the cast is that the C compiler already silently cast a void * into whatever pointer type you want, and so, doing it yourself is overkill and useless.
If you want to have type safety, you can either switch to C++ or write your own wrapper function, like:
int * malloc_Int(size_t p_iSize) /* number of ints wanted */
{
return malloc(sizeof(int) * p_iSize) ;
}
C++
Sometimes, even in C++, you have to make profit of the malloc/realloc/free utils. Then you'll have to cast. But you already knew that. Using static_cast<>() will be better, as always, than C-style cast.
And in C, you could override malloc (and realloc, etc.) through templates to achieve type-safety:
template <typename T>
T * myMalloc(const size_t p_iSize)
{
return static_cast<T *>(malloc(sizeof(T) * p_iSize)) ;
}
Which would be used like:
int * p = myMalloc<int>(25) ;
free(p) ;
MyStruct * p2 = myMalloc<MyStruct>(12) ;
free(p2) ;
and the following code:
// error: cannot convert ‘int*’ to ‘short int*’ in initialization
short * p = myMalloc<int>(25) ;
free(p) ;
won't compile, so, no problemo.
All in all, in pure C++, you now have no excuse if someone finds more than one C malloc inside your code...
:-)
C + C++ crossover
Sometimes, you want to produce code that will compile both in C and in C++ (for whatever reasons... Isn't it the point of the C++ extern "C" {} block?). In this case, C++ demands the cast, but C won't understand the static_cast keyword, so the solution is the C-style cast (which is still legal in C++ for exactly this kind of reasons).
Note that even with writing pure C code, compiling it with a C++ compiler will get you a lot more warnings and errors (for example attempting to use a function without declaring it first won't compile, unlike the error mentioned above).
So, to be on the safe side, write code that will compile cleanly in C++, study and correct the warnings, and then use the C compiler to produce the final binary. This means, again, write the cast, in a C-style cast.
One possible error it can introduce is if you are compiling on a 64-bit system using C (not C++).
Basically, if you forget to include stdlib.h, the default int rule will apply. Thus the compiler will happily assume that malloc has the prototype of int malloc(); On Many 64-bit systems an int is 32-bits and a pointer is 64-bits.
Uh oh, the value gets truncated and you only get the lower 32-bits of the pointer! Now if you cast the return value of malloc, this error is hidden by the cast. But if you don't you will get an error (something to the nature of "cannot convert int to T *").
This does not apply to C++ of course for 2 reasons. Firstly, it has no default int rule, secondly it requires the cast.
All in all though, you should just new in c++ code anyway :-P.
Well, I think it's the exact opposite - always directly cast it to the needed type. Read on here!
The "forgot stdlib.h" argument is a straw man. Modern compilers will detect and warn of the problem (gcc -Wall).
You should always cast the result of malloc immediately. Not doing so should be considered an error, and not just because it will fail as C++. If you're targeting a machine architecture with different kinds of pointers, for example, you could wind up with a very tricky bug if you don't put in the cast.
Edit: The commentor Evan Teran is correct. My mistake was thinking that the compiler didn't have to do any work on a void pointer in any context. I freak when I think of FAR pointer bugs, so my intuition is to cast everything. Thanks Evan!
Actually, the only way a cast could hide an error is if you were converting from one datatype to an smaller datatype and lost data, or if you were converting pears to apples. Take the following example:
int int_array[10];
/* initialize array */
int *p = &(int_array[3]);
short *sp = (short *)p;
short my_val = *sp;
in this case the conversion to short would be dropping some data from the int. And then this case:
struct {
/* something */
} my_struct[100];
int my_int_array[100];
/* initialize array */
struct my_struct *p = &(my_int_array[99]);
in which you'd end up pointing to the wrong kind of data, or even to invalid memory.
But in general, and if you know what you are doing, it's OK to do the casting. Even more so when you are getting memory from malloc, which happens to return a void pointer which you can't use at all unless you cast it, and most compilers will warn you if you are casting to something the lvalue (the value to the left side of the assignment) can't take anyway.
#if CPLUSPLUS
#define MALLOC_CAST(T) (T)
#else
#define MALLOC_CAST(T)
#endif
...
int * p;
p = MALLOC_CAST(int *) malloc(sizeof(int) * n);
or, alternately
#if CPLUSPLUS
#define MYMALLOC(T, N) static_cast<T*>(malloc(sizeof(T) * N))
#else
#define MYMALLOC(T, N) malloc(sizeof(T) * N)
#endif
...
int * p;
p = MYMALLOC(int, n);
People have already cited the reasons I usually trot out: the old (no longer applicable to most compilers) argument about not including stdlib.h and using sizeof *p to make sure the types and sizes always match regardless of later updating. I do want to point out one other argument against casting. It's a small one, but I think it applies.
C is fairly weakly typed. Most safe type conversions happen automatically, and most unsafe ones require a cast. Consider:
int from_f(float f)
{
return *(int *)&f;
}
That's dangerous code. It's technically undefined behavior, though in practice it's going to do the same thing on nearly every platform you run it on. And the cast helps tell you "This code is a terrible hack."
Consider:
int *p = (int *)malloc(sizeof(int) * 10);
I see a cast, and I wonder, "Why is this necessary? Where is the hack?" It raises hairs on my neck that there's something evil going on, when in fact the code is completely harmless.
As long as we're using C, casts (especially pointer casts) are a way of saying "There's something evil and easily breakable going on here." They may accomplish what you need accomplished, but they indicate to you and future maintainers that the kids aren't alright.
Using casts on every malloc diminishes the "hack" indication of pointer casting. It makes it less jarring to see things like *(int *)&f;.
Note: C and C++ are different languages. C is weakly typed, C++ is more strongly typed. The casts are necessary in C++, even though they don't indicate a hack at all, because of (in my humble opinion) the unnecessarily strong C++ type system. (Really, this particular case is the only place I think the C++ type system is "too strong," but I can't think of any place where it's "too weak," which makes it overall too strong for my tastes.)
If you're worried about C++ compatibility, don't. If you're writing C, use a C compiler. There are plenty really good ones avaliable for every platform. If, for some inane reason, you have to write C code that compiles cleanly as C++, you're not really writing C. If you need to port C to C++, you should be making lots of changes to make your C code more idiomatic C++.
If you can't do any of that, your code won't be pretty no matter what you do, so it doesn't really matter how you decide to cast at that point. I do like the idea of using templates to make a new allocator that returns the correct type, although that's basically just reinventing the new keyword.
Casting a function which returns (void *) to instead be an (int *) is harmless: you're casting one type of pointer to another.
Casting a function which returns an integer to instead be a pointer is most likely incorrect. The compiler would have flagged it had you not explicitly cast it.
One possible error could (depending on this is whether what you really want or not) be mallocing with one size scale, and assigning to a pointer of a different type. E.g.,
int *temp = (int *)malloc(sizeof(double));
There may be cases where you want to do this, but I suspect that they are rare.
I think you should put the cast in. Consider that there are three locations for types:
T1 *p;
p = (T2*) malloc(sizeof(T3));
The two lines of code might be widely separated. Therefore it's good that the compiler will enforce that T1 == T2. It is easier to visually verify that T2 == T3.
If you miss out the T2 cast, then you have to hope that T1 == T3.
On the other hand you have the missing stdlib.h argument - but I think it's less likely to be a problem.
On the other hand, if you ever need to port the code to C++, it is much better to use the 'new' operator.