Reglas de sintaxis typedef de C++
Frecuentes
Visto 658 veces
3
For the life of me I cannot find a good explanation of what are the rules that are used to convert a typedef to a C++ statement. The simple cases I understand. But consider this from Danny Kalev:
typedef char * pstr;
int mystrcmp(const pstr, const pstr); //wrong!
Danny Kalev then writes:
The sequence const pstr actually means char * const (a const pointer to char); not const char * (a pointer to const char.
I cannot find anywhere the rule to explain why "const pstr" would be converted to "char * const".
Gracias por cualquier ayuda.
2 Respuestas
5
Eso es porque pstr
es un alias para char*
y cuando lo hagas const pstr
es un poco como decir const (char*)
y no (const char)*
.
contestado el 22 de mayo de 12 a las 17:05
Thanks. This sheds some light on things. I still would be interested in knowing if there was documentation that shows that "const pstr" gets expanded to "const (char *)" and not "const char *". - Davids
3
A typedef isn't like a macro; it doesn't just perform simple text replacement. The typedef defines a single unit, and the additional const
applies to the entire thing. The unit defined is a pointer, so applying const
to it give you a const pointer.
The outcome you expected would require the const
to "reach inside" the pstr
type to apply to something internal. It would get worse the more pointer levels were declared inside that type. Consider typedef char*** pppstr
. To make that a char const***
, la const
would have to be inserted three levels deep dentro de pppstr
type. It's better for the rule to consistently apply const
to the outer level, no matter how complicated the type definition really is.
contestado el 22 de mayo de 12 a las 17:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c++ or haz tu propia pregunta.
This seems logical, no? You are defining
pstr
type as pointer to char. Soconst pstr
is a const pointer to char,char * const
. - arrowdSimple rule of thumb.
typedef
!=#define
. If you want what you are describing, you must use a macro. - Richard J. Ross IIIIf you use the post-const form consistently, it makes a lot more sense.
pstr const
==char * const
. The pre-const form is an exception and accordingly it can make things confusing. - Benjamin Lindley