C language collection (1): integer increase

Source: Internet
Author: User

Let's start with a simple piece of code:

  1 #include <stdio.h>  2   3 int array[] = {1, 2, 3, 4, 5, 6, 7};  4 #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))  5   6 int main()  7 {  8     int i = -1;  9     int x; 10  11     if(i <= TOTAL_ELEMENTS - 2) { 12         x = array[i + 1]; 13         printf("x = %d.\n", x); 14     } 15  16     printf("now i = %d.\n", TOTAL_ELEMENTS); 17  18     return 0; 19 }

Execution result:

Randy @ ubuntu :~ /C_Language $./a. out

Now I = 7.

Isn't it strange? Why is line13 x = not displayed ?.

Yes. There are three points worth noting in this small example:

1. sizeof () is an operator and the return type is unsigned, that is, non-negative.

2. The if statement is between singned int and unsigned int.Integer increaseRule. If all values of the original type are represented by the int type, the value is converted to the int type. Otherwise, the value is converted to the unsigned int type. Therefore, the I will be upgraded to the unsigned type.

3. I =-1 is upgraded to the unsigned type. What is the value? This is requiredInteger ConversionRule: as explained in K & R, the method to convert any integer to a specified number of unsigned numbers is: add 1 to the maximum value that can be expressed by the unsigned number type to find the smallest non-negative value that is the same as this integer. Listening to me, let's just put it bluntly. As long as you know the Binary Expression Method of the original integer, and then use the type to be converted to parse it, you will get the upgraded value. For example, if the negative value is-1 and the negative value is indicated by a complement code in the computer, the value is 0 xffffffff after being upgraded to the unsigned type, which is obviously larger than TOTAL_ELEMENTS (7.

--- End ---

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.