OC is an enhanced C feature, so it is basically consistent with C on variables and basic data types.
In OC, variable naming has the following rules:
Consists of letters, numbers, underscores, and $ symbols
Must start with a letter, underscore, $ symbol
Case sensitive
The reserved words of OC cannot be used when defining variables in OC, and the reserved words of OC are as follows:
The following basic data types are available in OC:
int: Declaring an integer variable
Double: Declaring a two-precision variable
float: Declaring floating-point variables
Char: Declaring a character-type variable
ID: Generic pointer type
Enum: declaring enum type
Long: Declares a variable or function of length integer
Short: Declaring a variable or function with a shorter integer
Signed: Declaring a signed type variable
struct: Declaring struct-body variables
Union: Declaring a common body (union) data type
Unsigned: Declaring an unsigned type variable
void: Declares that a function has no return value or no argument
Data type formatting characters:
Data type OC keyword format description boot character
integer int%d.%i
Short int%hd.%hi
Long, type long int%ld.%li
Unsigned short-integer unsigned int%u
No short integral type unsigned shorter%hu
unsigned long integer unsigned%lu
Float type float%f
Double-%f
Long Double%LF
Character Char-%c
Here is an example program:
[Plain] View plain copy
//
Main.m
Mxy01-datatype
//
Created by Mxy on 13-9-7.
Copyright (c) 2013 Mxy. All rights reserved.
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
Reserved words cannot be defined as variable names, such as int, float, and so on.
int i = 2;
float F = 2.3f;
Double d = 2.3e12;
char c = ' a ';
Output data
NSLog (@ "I:%d", i);
NSLog (@ "F:%f after interception:%.2f", f,f);
NSLog (@ "D:%e after interception:%.2e", d,d);
NSLog (@ "C:%c,%d", C, c);
Data conversion
Data type large size turns into small may lose precision
int i2 = (int) F;
float F2 = (float) i;
NSLog (@ "Data conversion");
NSLog (@ "I2:%d", i2);
NSLog (@ "F2:%f", F2);
NSLog (@ "Scope of the variable");
if (YES) {
int i3 = 2;
NSLog (@ "i3:%d", i3);
}
There is no access to the internal i3 variable outside of the IF {}, because the scope of the i3 variable is just the inside of the {}
NSLog (@ "i3:%d", i3);
/*
Run results
2013-09-07 22:47:52.655 mxy01-datatype[859:303] I:2
2013-09-07 22:47:52.667 mxy01-datatype[859:303] f:2.300000 after interception: 2.30
2013-09-07 22:47:52.672 mxy01-datatype[859:303] d:2.300000e+12 after interception: 2.30e+12
2013-09-07 22:47:52.674 mxy01-datatype[859:303] c:a, 97
2013-09-07 22:47:52.679 mxy01-datatype[859:303] Data conversion
2013-09-07 22:47:52.682 mxy01-datatype[859:303] I2:2
2013-09-07 22:47:52.685 mxy01-datatype[859:303] f2:2.000000
*/
}
return 0;
}
Objective-c variables and basic data types