Typedef in Objective C
Last Updated :
18 Jul, 2022
A typedef allows us to define a data type with a new name, for example, typedef unsigned char CAT. Now from now, onwards CAT can be used as an abbreviation for unsigned char, for example, CAT num1, num2;. Or in other words, we can say that typedef is a keyword that is used to assign the new name to the predefined or user-defined datatypes. Thus, you are allowed to customize the name for the predefined long names of data types. It will make the code more readable. The typedef is limited to giving symbolic names only to types. The computer performs the typedef interpretation. Or we can say that it creates an alias that can be used anywhere in place of a complex or long data type name.
The typedef identifier, when used in a declaration, specifies that the declaration is a typedef declaration rather than a variable or function declaration. Generally, the typedef identifier appears at the beginning of the declaration, although it can appear after type identifiers or between two type identifiers. A typedef declaration can declare one or more identifiers on the same line (eg, int and a pointer to int), it can declare array and function types, pointers and references, class types, etc. Each identifier introduced in this declaration becomes a type defame, which is synonymous with the type of object or function it would become if the typedef keyword were removed. The typedef specifier cannot be combined with any other specifier except typedef.
Syntax:
typedef unsigned long long BUTTON
Example 1:
ObjectiveC
#import <Foundation/Foundation.h>
typedef int MOUSE;
typedef unsigned long long CAT;
int main ( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init];
MOUSE x = 10000;
CAT y = 121234;
NSLog ( @"Value of x is %i" , x);
NSLog ( @"Value of y is %llu" , y);
[pool drain];
return 0;
}
|
Output:
Value of x is 10000
Value of y is 121234
Example 2:
ObjectiveC
#import <Foundation/Foundation.h>
typedef struct Author {
NSString *Title;
NSString *Publisher;
int Book_Number;
} Author;
int main()
{
Author author;
author.Title = @"How to grab internship at geeksforgeeks" ;
author.Publisher = @"Geek_1" ;
author.Book_Number = 342;
NSLog ( @"Book title : %@\n" , author.Title);
NSLog ( @"Book publisher : %@\n" , author.Publisher);
NSLog ( @"Book Id : %d\n" , author.Book_Number);
return 0;
}
|
Output:
Book title: How to grab an internship at geeksforgeeks
Book publisher: Geek_1
Book Id: 342
Difference between typedef and #define
typedef |
#define |
typedef is a compiler token |
#define is a preprocessor token |
typedef defines types. |
#define defines macros. |
The keyword called typedef can be used to give a type a new name. |
It is usually used while creating constants that represent numbers, strings, and expressions. |
It is limited to some symbolic names to type |
It is used to define an alias for values also. |
Share your thoughts in the comments
Please Login to comment...