Is this undefined behavior in C to use a pointer to typedef as a pointer to a primitive type?
Let's assume you have the following code:
#include <stdio.h>
typedef int myIntType;
int main()
{
int a;
myIntType *ptr = &a;
*ptr = 1;
printf("%d\n", a);
return 0;
}
Is this causing undefined behavior?
With any reasonable interpretation, I would expect this to just set the value a
to, 1
and therefore print the string 1
to stdout
.
Compiling with gcc -Wall -Wextra -pedantic main.c -o main
on Mac OS X produces no errors or warnings and produces the expected result when executed.
My question is purely theoretical, and I do not intend to use such a construction in real code.
source to share
From cppreference.com about the typedef specifier:
The typedef ... specifier can declare array and function types, pointers and references, class types, etc. Each identifier entered in this declaration becomes a typedef-name, which is a synonym for an object or function type, as if the typedef keyword was removed.
In other words, it is exactly the same as if you removed your own type and replaced it with int
. So this is clear behavior. int
and myIntType
are 100% interchangeable.
This is actually a C ++ reference. From K&R, chapter 6.7 to typedef
:
C provides a named object
typedef
for creating new data type names. For example, a declarationtypedef int Length;
makes the nameLength
synonymousint
. The typeLength
can be used in ads, casts, etc. Just like the typeint
.
Remember, K&R is not the most current standard. Another answer refers to the current standard. As far as I know, typedef
it hasn't changed.
source to share
In your example, is the myIntType *
same as int *
.
Section 6.7.8 of the C standard provides an example:
4 EXAMPLE 1 After
typedef int MILES, KLICKSP(); typedef struct { double hi, lo; } range;
constructions
MILES distance; extern KLICKSP *metricp; range x; range z, *zp;
- all valid ads. The type
distance
isint
, and the typemetricp
is "a pointer to a function without a specification of the return parameterint
", andx
andz
is the given structure;zp
is a pointer to such a structure. The objectdistance
is of a type compatible with any other objectint
.
source to share