Arithmetic conversion for C (casting rules for arithmetic operations)

Source: Internet
Author: User

First two links to explain my doubts:

Http://en.cppreference.com/w/cpp/language/operator_arithmetic

Https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx

At first I was looking at <<expert C programming-Deep C secrets>> This book (Chinese translation c expert programming), Chapter 1 inside how quite was a quite change this section , there is a code like this:

#include <stdio.h>

intMain ()
{
if(-1< (unsignedChar)1)
printf"-1 is less than (unsigned char) 1:ansi semantics.\n");
Else
printf"-1 is not less than (unsigned char) 1:k&r semantics.\n");
return0;

}

I used vs2013 and GCC 4.9.1 to compile and run separately, which is the semantics of ANSI. Prints the first statement.

and change it.

#include <stdio.h>


intMain ()
{
if(-1< (unsignedint)1)//or a unsigned .
printf"1111111111.\n");
Else
printf"222222222222222.\n");
return0;
}

The result of the GCC 4.9.1 compilation run (without any special compilation options) is to print the second article. The vs2013 default compilation does not pass, error: Negative numbers are converted to unsigned numbers.

Start looking at <<expert C programming--deep C secrets>> This book is a bit lazy here, only remember these two words:

Operands with different types get converted when you do arithmetic. Everything is converted to the type of the floatest, longest operand, signed if possible without losing bits.

The whole rule is actually the two links at the beginning of this article.

I think the best practice should be as few as possible to cast, who want to remember those boring rules.

Arithmetic conversion for C (casting rules for arithmetic operations)

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.