Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c - Is conversion from unsigned to signed undefined?

void fun(){
    signed int a=-5;
    unsigned int b=-5;
    printf("the value of b is %u
",b);
    if(a==b)
         printf("same
");
    else
         printf("diff");
}

It is printing :

4294967291

same

In the 2nd line signed value is converted to unsigned value. So b has the value UINTMAX + 1 - 5 = 4294967291.

My question is what is happening in the comparison operation .

1) Is a again converted to unsigned and compared with b ?

2) Will b(ie unsigned ) be ever casted to signed value and compared automatically?

3) Is conversion from unsigned to signed undefined due to int overflow ?

I have read other posts on the topic. I just want clarification on questions 2 and 3 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) Is a again converted to unsigned and compared with b ?

Yes. In the expression (a==b), the implicit type conversion called "balancing" takes place (the formal name is "the usual arithmetic conversions"). Balancing rules specify that if a signed and a unsigned operand of the same size and type are compared, the signed operand is converted to a unsigned.

2) Will b(ie unsigned ) be ever casted to signed value and compared automatically?

No, it will never be converted to signed in your example.

3) Is conversion from unsigned to signed undefined due to int overflow ?

This is what the standard says: (C11)

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

In other words, if the compiler can manage to do the conversion in 2) above, then the behavior is well-defined. If it cannot, then the result depends on the compiler implementation.

It is not undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...