typedef - Why this C program complies and runs -
with curiosity of definition , scope of typedef
have written below c code in 2 .c files:
main.c
#include <stdio.h> int main() { int = 5, b = 6; printf("a = %d, b = %d\n", a, b); swap(&a, &b); printf("a = %d, b = %d\n", a, b); }
swap.c
typedef t; void swap(t* a, t* b) { t t = *a; *a = *b; *b = t; }
to surprise, code files compiled visual studio c compiler (cl.exe /tc main.c swap.c
)
and program runs correctly! understanding, typedef
requires 2 parameters, why code compiles , runs?
for further analysis, in main function, declared 2 float variables , try swap both after swapping 2 integers, time fails compile (with cl.exe). amazing code compiled , run tiny c (tcc.exe main.c swap.c
), works template method!
typedef declaration (it creates aliases existing types), , in no way limited 2 'parameters'. see typedef declarations (c) , fundamental typedef operand syntax.
if write typedef t;
, declaring t unspecified type (called "no specified type" in c89 spec). it's little (and little, conceptually might you) #define x
defines x
preprocessor replace empty string (i.e. remove x
).
so, typedef
ing t
unspecified, makes arguments swap
function of unspecified type.
what seeing here in c89 (but not c99, results in undefined behaviour - contrast ansi 3.5.2 isoc99 6.7.2), unspecified types default int
, why method works integers not floats in visual studio (presumably disallows implicit integer typing default). gcc compile floats, though, provided aren't using -werror
, should be.
i suggest turning on warnings: -wall
in gcc spit out following, among other things
swap.c:1:9: warning: type defaults ‘int’ in declaration of ‘t’ [-wimplicit-int]
the reason "works" on floats because floats , ints same size (32 bits) on machine. try double. or char. or short.
swap
this:
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
with calling
swap((int*)&a, (int*)&b);
try , compare results yourself.
edit: tried in tcc. -wall
not alert implicit int typing, sadly.
Comments
Post a Comment