I know simple definition of typedef :
typedef is a keyword in C to assign alternative names to types.
Following this definition I tried to implement typedef as following :
int main()
{
typedef long mylong; //as per my knowledge after this statement mylong will be treated as long
int long b; // this works fine
int mylong c; // but this gives error
}
I tried this on gcc. And following is the error 
I know this error means I didn't get actual concept of typedef. Can anybody please tell me where I am wrong?
Unlike #define, typedef is a mechanism for introducing a new name for a type, as opposed to a textual substitution.
Recall that types long int, int long, and long are three synonyms that refer to the same C type. When you use typedef, you make another synonym referring to that same type.
When you use it like this
mylong x = 123;
the usage is correct: mylong is used like a name of a type. However, when you try using it in combination with int, like this
int mylong x = 123;
the compiler reports an error because int mylong does not name a valid type. To the compiler it looks the same as if you wrote, say int float x = 5 or struct mystruct int z = ....
When you omit the type in C, it's assumed int
So typedef long mylong; is the same as typedef long int mylong;.
Making the offending line be something like this:
int long int c;
Hence the error.
The typedef is a new type* (not text substitution for long). So you don't need to add an int to make a variable of that type. A simple mylong c; will suffice.
*Well, it's a bit more involved than that. The new type is in fact the same as a regular long int, and the two are interchangeable. But for sound domain logic, you should treat it as a new seperate type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With