+ 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?

2nd Feb 2017, 1:19 PM
Ishan Sharma
Ishan Sharma - avatar
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;
2nd Feb 2017, 1:48 PM
lulugo
lulugo - avatar
+ 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 !
2nd Feb 2017, 3:19 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
+ 1
@Etienne Yeah, you're totally right. I mixed something up there. I actually meant a unsigned char. Thank you for the correction :)
2nd Feb 2017, 6:54 PM
lulugo
lulugo - avatar