+ 1
Is any use of typedef in C++?
it is used to create alternate names to pre defined data types but what is the use of giving alternate name?
3 Respuestas
+ 1
You can make them shorter to make your code better readable.
A good example are for example the unsigned datatypes. They are pretty long to write. Instead you can just use typedefs:
typedef unsigned int uint;
typedef unsigned short byte;
...
uint a = 8;
+ 1
In addition to @lulugo's answer (which I wholeheartedly agree with except for typedef'ing an unsigned short as a byte - an unsigned short is 2 bytes so it would normally be named 'ushort'; an unsigned char is 1 byte and typically renamed as 'byte' - but I suspect he just typed without thinking!) there is an additional case where this applies - function pointers as function parameters:
For example:
typedef int (*pFunc)(int x, int y);
int bar(int x, int y, pFunc f){return f(x, y);}
This can be called something like this:
int foo(int a, int b){return a+b;}
int z = bar(3, 4, foo);
It is very cumbersome to not use typedefs for function pointer arguments like this, especially if you have a lot of functions that take an argument of type pFunc !
+ 1
@Etienne
Yeah, you're totally right. I mixed something up there. I actually meant a unsigned char.
Thank you for the correction :)