Typedef - Objective C
The Objective C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers.
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows:
You can use the typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:
typedef vs #define
The #define is a objective C directives, which is also used the aliases for various data types similar to typedef but with following difference.
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:
BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows:
typedef unsigned char byte;
You can use the typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:
#import <Foundation/Foundation.h>
typedef struct Books
{
NSString *title;
NSString *author;
NSString *subject;
int book_id;
} Book;
int main( )
{
Book book1;
book1.title = @"Objective C programming";
book1.author = @"Rjtenos ";
book1.subject = @"Programming tuts";
book1.book_id = 100;
NSLog(@"Book title :%@\n", book1.title);
NSLog(@"Book title : %@\n", book1.author);
NSLog(@"Book title : %@\n", book1.subject);
NSLog(@"Book title : %d\n", book1.book_id);
return 0;
}
typedef struct Books
{
NSString *title;
NSString *author;
NSString *subject;
int book_id;
} Book;
int main( )
{
Book book1;
book1.title = @"Objective C programming";
book1.author = @"Rjtenos ";
book1.subject = @"Programming tuts";
book1.book_id = 100;
NSLog(@"Book title :
typedef vs #define
The #define is a objective C directives, which is also used the aliases for various data types similar to typedef but with following difference.
- The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE etc.
- The typedef interpretation is performed by the compiler where as #define elemenets are processed by the preprocessor.
#import <Foundation/Foundation.h>
#define TRUE 1
#define FALSE 0
int main( )
{
NSLog(@"Value of TRUE : %d\n", TRUE); NSLog(@"Value of FALSe : %d\n", FALSE);
return 0;
}
#define TRUE 1
#define FALSE 0
int main( )
{
NSLog(@"Value of TRUE : %d\n", TRUE); NSLog(@"Value of FALSe : %d\n", FALSE);
return 0;
}
No comments: