With curiosity of the definition and scope of typedef
I have written below C code in 2 .c files:
main.c
#include <stdio.h>
int main()
{
int a = 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 my surprise, the code files could be compiled with Visual Studio C compiler (cl.exe /Tc main.c swap.c
)
And the program runs correctly! From my understanding, typedef
requires 2 parameters, but why this code compiles and runs?
For further analysis, in the main function, I declared another 2 float variables and try also to swap both after swapping the 2 integers, but this time it fails to compile (with cl.exe). What amazing is the code could be compiled and run with Tiny C (tcc.exe main.c swap.c
), so it works like a template method!