differences between node* pointer and node *pointer in C? [duplicate] - c

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What makes more sense - char* string or char *string?
Pointer declarations in C++: placement of the asterisk
I've seen mixed versions of this in a lot of code. (This applies to C and C++, by the way.) People seem to declare pointers in one of two ways, and I have no idea which one is correct, of if it even matters.
The first way it to put the asterisk adjacent the type name, like so:
someType* somePtr;
The second way is to put the asterisk adjacent the name of the variable, like so:
someType *somePtr;
This has been driving me nuts for some time now. Is there any standard way of declaring pointers? Does it even matter how pointers are declared? I've used both declarations before, and I know that the compiler doesn't care which way it is. However, the fact that I've seen pointers declared in two different ways leads me to believe that there's a reason behind it. I'm curious if either method is more readable or logical in some way that I'm missing.

It's a matter of preference, and somewhat of a holy war, just like brace style.
The "C++" style
someType* somePtr;
is emphasizing the type of the pointer variable. It is saying, essentially, "the type of somePtr is pointer-to-someType".
The "C" style
someType *somePtr;
is emphasizing the type of the pointed-to data. It is saying, essentially, "the type of data pointed to by somePtr is someType".
They both mean the same thing, but it depends on if a given programmer's mental model when creating a pointer is "focused", so to speak, on the pointed-to data or the pointer variable.
Putting it in the middle (as someType * somePtr) is trying to avoid committing to either one.

It doesn't matter. Someone will now come along and close the question as a dupe, and someone else will show how the int* a way breaks if you declare multiple variables in the same declarations while int *a better reflects the syntactical structure of the code, and another one will show that Stroustrup prefers the int* a way and keeps the type together on the left side.
Many opinions, but no "right" way here.

It doesn't matter, it is personal preference.
Some people like to keep the type together:
int* p;
Other people say that it should go next to the variable because of the following:
int *p, x;//declare 1 int pointer and 1 int
int *p, *x;//declare 2 int pointers.
Over time you will just overlook this and accept both variations.

The difference arose because C++ added a stronger type system on top of C.
C style
A C programmer usually thinks in terms of "values," so
int *pValue;
reads "the dereference of pValue is an int".
C++ style
Whereas a C++ programmer thinks in "types" so
int* pValue;
reads "the type of pValue is pointer to int".
The compiler sees no difference at all of course. However you will find that it is the C programmers who insist on "value semantics" when programming in C++.

I think putting the asterisk adjacent to the name of the variable is clearer.
You might mistakenly declare someType* one, two; thinking that they are both pointers but only the variable one is a pointer; two is just a someType. Declaring as someType *one, *two avoids this problem.

Every single way I've seen ever is
TheType *myPointer
because you are declaring a POINTER of type TheType. Similar declaring
TheType myVar
would be declaring an instance variable of type TheType.
Also you can then clearly do this and have it easily readable
TheType myVar, *myPointer;

Related

How create user-defined types in C?

For unknown reasons, I need to know how to replace the standard char a[10]; with string a; (Yes, I saw it in the CS50). So, how to create your own variable type named string?
Amplifying on what #Lundin said in his answer:
One of the things that makes C hard to learn -- especially for students coming from other languages -- is that C does not have a first-class "string" type. Important as they are, strings in C are cobbled together out of arrays of char, and often accessed via char * pointers. The cobbling together is performed by a loose collaboration between the compiler, the programmer, and library functions like strcpy and printf.
Although I said that "strings are cobbled together out of arrays of char, and often accessed via char * pointers", this does not mean that C's string type is char [], and it also does not mean that C's string type is char *.
If you imagine that C has a first-class string type, handled for you automatically by the language just like char, int, and double, you will be badly confused and frustrated. And if you try to give yourself a typedef called string, this will not insulate you from that confusion, will not ease your frustration, will not make your life easier in any way. It will only cloud the issue still further.
It is as simple as typedef char string[10];.
But please don't do this. Hiding arrays or pointers behind a typedef is very bad practice. The code gets much harder to read and you gain nothing from it. See Is it a good idea to typedef pointers? - the same arguments apply to arrays.
It is particularly bad to name the hidden array string since that is the exact spelling used by C++ std::string.
Please note that the CS50 is a bad course since it teaches you to do this. The SO community is sick and tired of "un-teaching" bad habits to the victims of this course. Stay away from questionable Internet tutorials in general.
If you want to create some manner of custom string type, the correct and proper way is to use a struct instead.
User defined types in C are structures, unions, enumerations and functions. And it seems you can also include arrays in the list.
For example
struct Point
{
int x;
int y;
};
or
enum Dimension { N = 100 };
Point a[N];
In this example the array type is Point[N].
In fact any derived type (including pointers) can be considered as a user-defined type. The C Standard does not define and use the tern user-defined type.
User defined types are one of the following: struct, union or enum. For example, struct:
struct worker {
int id;
char firstName[255];
char lastName[255];
};
To create an instance:
struct worker w1 = { 1234, "John", "Smith" };

How to translate an empty C struct inside struct to Delphi?

How to literally translate the following empty C struct inside struct to Delphi (from winnt.h):
typedef struct _TP_CALLBACK_ENVIRON_V3 {
...
struct _ACTIVATION_CONTEXT *ActivationContext;
...
} TP_CALLBACK_ENVIRON_V3;
I'm inclined to use just Pointer since this structure must not be manipulated and it's a pointer anyway. I'm just curious how would one translate it literally (if possible). I was thinking about something like this:
type
PActivationContext = ^TActivationContext;
TActivationContext = record
end;
TTPCallbackEnvironV3 = record
...
ActivationContext: PActivationContext;
...
end;
But, you know, an empty record... So, how would you literally translate the above structure to Delphi ?
The C struct is what is known as an incomplete type. The C code is a common technique used to implement an opaque pointer. By implementing it this way in C you have type safety in the sense that variables of type struct _ACTIVATION_CONTEXT* are not assignment compatible with other pointers. Well, apart from void* pointers which are assignment compatible with all pointer types.
In Delphi there is no such thing as an incomplete type. So I think that the best solution is exactly what you have proposed. It's not particularly important to mimic the C code exactly. What you are aiming for is to have the benefits, specifically type safety. And what you propose is probably as good as you will get.
On the other hand, it depends how visible this type is. If it is very private, perhaps declared only in the implementation section of a unit, and used sparingly, then you may take the stance that declaring an empty record is a little over the top. You may conclude that PActivationContext = Pointer is reasonable.

How are these two pointers different from each other?

I'm new to C language and pointers in general. So my understanding of these two things is basic.
I've been trying to create a structure that hold pointers to functions, nothing fancy. While doing so; I noticed that this statement:
int *func()
doesn't work. while this one actually works:
int (*func)()
What's the difference between them? Is it because the first statement is only a pointer to integer. while the other pointer, somehow, points to a function? How so?
int *func(void)
Defines a function named func that has no parameters and returns a pointer to an integer
int(*func)(void)
Defines a pointer to a function that has no parameters and returns an integer
The reason for this difference is operator precedence. Parerenteses have a higher precendence than *. Therefore in the first expression int *func() the function-parenthesis have the highest precedence and are considered first, so associate with the symbol func so the compiler knows that func is a symbol for a function. Therefore the rest is the return.
In the second instance int(*func)() there is an extra set of parenthesis. Inside the first parenthesis we see *func. As the parenthesis is the highest precendence (left-to-right) the compiler must interpret the contents of this set... *func is a pointer. OK a pointer to what? Look right and we see () so it is a pointer to a function. Then look left to see the return type.
Hope this makes sense :) Also try How to interpret complex C/C++ declarations on CodeProject.com. It talks about something called the "Right-left rule", which is "...a simple rule that allows you to interpret any declaration...". It's a little more than half way down the page...
Also try cdecl: C gibberish ↔ English. It's quite a nice implementation of the cdecl utility.

Why making an empty struct a new typedef and using it as a pointer type?

I have a header and a sample application using this header, all in C, I get almost all the logic of this software except for this; this the interesting part of the header:
struct A;
typedef struct A A;
in the C application this A is only used when declaring a pointer like this
A* aName;
I'm quite sure that this is a solution for just including A in the scope/namespace and give just a name to a basically void pointer, because this kind of pointer is only used to handle some kind of data, it is more like some namespace sugar.
What this could be for?
You're correct that it's like a void pointer, in that void is an incomplete type, and in this file A is also an incomplete type. About all you can do with incomplete types is pass around pointers to them.
It has one advantage over void* in this file, that it's a different and incompatible type from some other bit of code that has done the same thing with B. So you get a bit of type safety. If A is windowHandle and B is jpgHandle, then you can't pass the wrong one to a function.
It has an advantage over void* in the .c file that defines the functions that accept an A* -- that file can contain a definition of struct A, and give A whatever members it wants, that the first file doesn't need to know about.
However, you say there are no other mentions of A in any header file, which means there are no functions that accept or return it. You also say that the only use of A in your source file is to declare pointers -- I wonder where the values of those pointers come from, if any.
If all that happens if that someone defines an uninitialized A* and never uses it, then clearly this is a remnant of some old code, or the start of some code that never got written, and it shouldn't be in the file at all.
Finally, if the real type is called something a bit less stupid than A, then the name might give a clue to its use.
I assume struct A is a forward declaration. It most likely is defined in one of the .c-files.
Doing so struct A's members are private to the module defining it.
This is an example of an opaque pointer, which is useful for passing handles. See http://en.wikipedia.org/wiki/Opaque_pointer for some further info. What may be interesting here from a C++ perspective, is the notion that you can define a class with a member that is a pointer to an (as yet) undefined struct. Although this struct is thus not yet defined in the header, in some later cpp implementation this struct is given body, and the compiler does the rest. This strategy is also called the Pimpl idiom (more of which you will find LOTS on the internet). Microsoft discusses it briefly at http://msdn.microsoft.com/en-us/library/hh438477.aspx.

Is typedef'ing a pointer type considered bad practice? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Typedef pointers a good idea?
I've seen this oddity in many APIs I have used:
typedef type_t *TYPE;
My point is that declaring a variable of type TYPE will not make it clear that in fact a pointer is declared.
Do you, like me, think that this brings a lot of confusion? Is this meant to enforce encapsulation, or there are other reasons as well? Do you consider this to be a bad practice?
In general, it's a bad practice. The significant problem is that it does not play well with const:
typedef type_t *TYPE;
extern void set_type(TYPE t);
void foo(const TYPE mytype) {
set_type(mytype); // Error expected, but in fact compiles
}
In order for the author of foo() to express what they really mean, the library that provides TYPE must also provide CONST_TYPE:
typedef const type_t *CONST_TYPE;
so that foo() can have the signature void foo(CONST_TYPE mytype), and at this point we have descended into farce.
Hence a rule of thumb:
Make typedefs of structs (particularly incomplete structs), not pointers to those structs.
If the definition of the underlying struct is not to be publicly available (which is often laudable), then that encapsulation should be supplied by the struct being incomplete, rather than by inconvenient typedefs:
struct type_t;
typedef struct type_t type_t;
void set_type(type_t *);
int get_type_field(const type_t *);
A common idiom is to suffix the type with _p to indicate that it's a pointer while still retaining the pointery qualities.
Sometimes it is necessary to use only the pointer type if the struct that it is pointing to is not publicly available. This helps facilitate data hiding. I.e.
typedef struct hidden_secret_object * object;
void change_object(object foo);
this allows you to change the way that hidden_secret_object is structured without breaking external code.
I don't find it clear either. I'm not fond of full capitalised types either (I try to reserve those for #defines).
This way makes it easy to kid oneself by thinking it is in fact a value type, while we're talking about a pointer type. The pointer type can be completely abstracted away with smart pointers, but that isn't common practise in C.
Suffixing with (as mentioned previously) _p, _ptr, Pointer or anything along those lines creates clarity; increases typing, that's true, but will prevent you from silly mistakes (such as using '.' instead of '->', ...) costing you valuable developing time.
It depends on what you are trying to achieve. There is no meaningful "yes or no" answer to your question the way it is stated.
If you are trying to create an abstract handle kind of type, implying that the user is not supposed to know or care what is hiding behind the type, then typedef-ing a pointer type is perfectly fine. The whole point is that today it might be a pointer type, and tomorrow it might become an integer type, and later it might become something else. This is exactly what pointer type typedefs are normally used for in most library interfaces.
You are saying that sometimes it is "not clear that a pointer is declared". But under this usage model that's exactly the point! It is supposed to be "not clear". The fact that the type happens to be an obfuscated pointer is none of your business. It is something that you don't need to know and not supposed to rely upon.
A classic example of this usage model is the va_list type in the standard library. In some implementation it might easily be a typedef for a pointer type. But that's something you are not supposed to know or rely upon.
Another example would be the definition of HWND type in Windows API. It is a typedef for pointer type as well, but that's none of your business.
A completely different situation is when you are typedef-ing a pointer type as a form of shorthand, just to make the declarations shorter for not having to type the * character every time. In this case the fact that the typedef is (and will always be) standing for a pointer type is exposed to the user. Normally this usage is not a good programming practice. If the users will want to create an alias to avoid typing * every time, they can do it by themselves.
This usage model usually leads to more obfuscated code for the reasons you already mentioned in your OP.
Example of this bad usage of typedefs can also be found in Windows API. Typedef names like PINT follow exactly that flawed usage model.
I don't think it's bad practice if the it's a pointer to an incomplete type, or if for any other reason the user isn't expected to dereference it. I never understood FILE*.
I also don't think it's bad practice if you're doing it because you have several levels of indirection, and you want to use it in situations where some of them are irrelevant. typedef char **argarray, or something.
If the user is expected to dereference it then in C, I think it's probably best to retain the *. In C++, people are used to user-defined types with overloaded operator*, such as iterators. In C that's just not normal.
Storage-class qualifiers like 'const' will work differently with typedef'ed pointers than with 'natural' ones. While this isn't typically a good thing with 'const', it can be very useful with compiler-specific storage classes like "xdata". A declaration like:
xdata WOKKA *foo;
will declare "foo" to be a pointer, stored in the default storage class, to a WOKKA in xdata. A declaration:
xdata WOKKA_PTR bar;
would declare "bar" to be a pointer, stored in xdata, to a WOKKA in whatever storage class was specified in WOKKA_PTR. If library routines are going to expect pointers to things with a particular storage class, it may be useful to define those storage classes within the pointer types.
It's bitten me in the ass on occasion:
for (vector<typedef_name_that_doesnt_indicate_pointerness_at_all>::iterator it;
it != v.end(); ++it)
{
it->foo(); // should have been written (*it)->foo();
}
The only time it's acceptable is if the type is meant to be truly opaque and not accessed directly at all. IOW, if someone's going to have to dereference it outside of an API, then the pointerness should not be hidden behind a typedef.
Maybe a way to make it more specific would be to call the new pointer type type_ptr or something like that:
typedef type_t* type_ptr;

Resources