Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why typedef is not working here?

Tags:

c

typedef

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

enter image description here

I know this error means I didn't get actual concept of typedef. Can anybody please tell me where I am wrong?

like image 249
A.s. Bhullar Avatar asked Dec 06 '22 01:12

A.s. Bhullar


2 Answers

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 = ....

like image 156
Sergey Kalinichenko Avatar answered Dec 08 '22 14:12

Sergey Kalinichenko


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

like image 30
StoryTeller - Unslander Monica Avatar answered Dec 08 '22 15:12

StoryTeller - Unslander Monica