6
I’ve seen one
MinhaEstrutura *
be explicitly typed as
typedef MinhaEstrutura * pMinhaEstrutura;
Why not always do so and get rid of having to dereference?
6
I’ve seen one
MinhaEstrutura *
be explicitly typed as
typedef MinhaEstrutura * pMinhaEstrutura;
Why not always do so and get rid of having to dereference?
5
It’s all about semantics. What’s the point of your code? Should he know there’s a pointer there? So leave the pointer exposed and do not create a type to render the pointer opaque. Creating a type like this indicates that you should not mess with pointer.
If the intention is not to show that there is a pointer there, why use the prefix p
in the type that is the Hungarian pointer notation? The biggest mistake is there. Unless the intention was to show that it is a pointer, there the typedef
should not be used.
In fact it won’t clear up "derreferenciar", so it’s not so opaque:
#include <stdio.h>
typedef struct { int x; } MinhaEstrutura;
typedef MinhaEstrutura * MeuTipo;
int main(void) {
MinhaEstrutura dado = { 1 };
MeuTipo var = &dado; //teve que usar o operador para pegar o endereço
printf("%d", var->x); //teve que usar -> para acessar o membro
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
It is possible for the compiler to treat the pointer transparently, but in C and C++ this is not done, so it is rarely advantageous to try opacity. Conform to the language where pointers are everywhere or change language.
In C++ it is easier to render opaque. What some people do is let the pointer within a type and its access be done through overloaded operators, but it is not a simple typedef
that will solve.
Browser other questions tagged c c++ pointer typing
You are not signed in. Login or sign up in order to post.