0

I'm not entirely sure what this is called, but I think it is very easy to do.

I have seen some people rename the types of variables to make their code easier to read. Let's say I have a shop of items and they need a int "itemId".

How could I define so that I can say:

Item getItem(ID itemId);

Insteath of:

Item getItem(int itemId);

I don't nessesarily know if it's any useful to always change code like that. But I would at the very least want the knowledge to know how to do it. Anyways, I'm quite sure it's almost as easy as:

#define ID as int;

or something in that manner. But I just were not able to look it up as I don't remember what the action is called x) Thanks

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Aleksander Fimreite
  • 1,439
  • 2
  • 18
  • 31

2 Answers2

2

C++11:

using ID = int;

C++11 and previous standards:

typedef int ID;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    I do have c++11, can also get the 12th edition from my school. But I assume the c++11 version is preferred over the older ones then, since they changed it? – Aleksander Fimreite Dec 04 '13 at 21:49
  • 1
    @AleksanderFimreite whether it is preferred in this case is still a matter of opinion. But `using` lets you do come [interesting stuff with templates](http://en.cppreference.com/w/cpp/language/type_alias), and that, together with this simple non-template case are somehow unified by syntax. So I expect more people will use the C++11 version as they get used to it. – juanchopanza Dec 04 '13 at 21:54
1

both #define ID int and typedef int ID can work and will have the same effect in your example; But there are differences between the two: the first defines a string literal which will be replaced with "int" at compile time, while the second defines a new data type. The later is the recommended way, as it is less error prone.

Pandrei
  • 4,843
  • 3
  • 27
  • 44