Objective-C type conversion and objective-c type conversion

Source: Internet
Author: User

Objective-C type conversion and objective-c type conversion

Type conversion usually refers to a variable, which is converted from one type to another. For example, to convert a long type to an int type

Use the following method:

(type_name) expression

 

In Objective-C, we usually use CGFloat for floating point operations. 32 bits are float type, 64 bits are double type, and the conversion method is usually

Follow these steps:

#import <Foundation/Foundation.h>int main(){   int sum = 17, count = 5;   CGFloat mean;   mean = (CGFloat) sum / count;   NSLog(@"Value of mean : %f\n", mean );   return 0;}

The result of the above code compilation and execution:

2013-09-11 01:35:40.047 demo[20634] Value of mean : 3.400000

Here, we will explain that the type conversion priority of a variable is higher than the division, that is, sum is converted to the double type first (64-bit), and division is calculated based on the generated double value.

Type conversion can be implicit and automatically executed by the compiler.

 

The following code converts the int type to the following code:

#import <Foundation/Foundation.h>int main(){   int  i = 17;   char c = 'c'; /* ascii value is 99 */   int sum;   sum = i + c;   NSLog(@"Value of sum : %d\n", sum );   return 0;}

The result of the above code compilation and execution:

2013-09-11 01:38:28.492 demo[980] Value of sum : 116

Sum is 116, because the compiler converts 'C' into ascii values before performing the actual addition operation.

 

The general data conversion process is generally from low to high. If it is from high to low, data will be lost. As shown in:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.