4_Objective-C Variables

A variable is name given to a storage area that our programs can manipulate.

Variable Specifications

  • Each variable in Objective-C has a specific type
  • Variable can be composed of letters, digits, and the underscore character.
  • It must begin with either a letter or an underscore.
  • Upper and lowercase letters are distinct

Variable Definition

Means to tell the compiler where and how much to create the storage for the variable.

Syntax

type variable_list;
  • type must be a valid Objective-C data type
  • variable_list may consist of one or more identifier names separated by commas.
int    i, j, k;
char   c, ch;
float  f, salary;
double d;

Note : Variables can be initialized (assigned an initial value) in their declaration.

type variable_name = value;

Examples

int d = 3, f = 5;           // definition and initializing d and f. 
byte z = 22;                // definition and initializes z. 
char x = 'x';               // the variable x has the value 'x'.

Note : For definition without an initializer:

  • variables with static storage duration are implicitly initialized with NULL
  • (all bytes have the value 0); the initial value of all other variables is undefined.

Variable Declaration

A variable declaration is useful when you are using multiple files and you define your variable in one of the files, which will be available at the time of linking of the program.

The extern keyword

You will use extern keyword to declare a variable at any place.

extern int d = 3, f = 5;    // declaration of d and f. 

Example 

Variables declaring defining and initializing

Lvalues and Rvalues in Objective-C:

There are two kinds of expressions in Objective-C:

Lvalue

  • Refer to a memory location
  • Called left-hand or right-hand side of an assignment.
int g = 20;

Rvalue

  • Refers to a data value that is stored at some address in memory
  • Cannot have a value assigned to it
  • Rvalue may appear on the right- but not left-hand side of an assignment.
  • Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side.
10 = 20;

Note : a valid statement and would generate compile-time error:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: