typedef of a previously defined typedef
second level typedef definition of a previously defined typedef.
Learning Objectives
- Use of typedef as second level of deinition for a previously defined typedef.
Source Code
|
Run Output
Code Understanding
typedef int score;
This is a type definition of score which would be of int type. Since this is defined outside main, so it can if used in any functions in the given file.
int main(){
score team1=10,team2=12;
We are using defined type score for declaring two variables team1 and team2 which will definitely be of int primary type only.
typedef score rank;
This is second level of typedef where score is already a predefined typedef and which can further define a new typedef for rank. Obviously both user defined data types score and rank will be of primary type int only. Advantage is that if typedef of score is changed, it will automatically change the typedef of rank also. This definition was done within the scope of main so it can be used within main routine only.
rank tr1,tr2;
These are two variable of secondary definition rank.
if(team1>team2) { tr1=1;tr2=2; } else { tr1=2;tr2=1; }
cout<<“Rank Team 1 = “<<tr1<<endl;
cout<<“Rank Team 2 = “<<tr2<<endl;
This is simply display of values based on out definition of datatypes.
return 0;
}
Notes
- When typedef is used, the standard primitive type can still be used. For e.g. double can still be used for definitions.
- Mostly it is good to define typedef as a global definition as similarity of datatypes are needed for the whole program.
Common Errors
- Sometime student write primitive data type after the friendly name. The standard syntax is –
typedef <primitive datatype> <friendly name> - For second level of typedef the standard syntax is
typedef <previously defined friendly name> <new friendly name>
Suggested Filename(s): tdoftd.cpp, typedefoftypedef.cpp
sunmitra| Created: 27-Aug-2018 | Updated: 28-Aug-2018|