Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function: assign unsigned variable to a function with a signed parameter

Tags:

c

casting

I recently came up with a question. Let's say we have:

void test(int32_t b){
    printf("value is %d", b);
}

int main(){
    uint32_t a = 43;
    test(a);  
   return 0;
}

What happens when you pass a unsigned variable to a signed parameter? How does the copy of the value work, and how does the cast work?

Can someone explain it to me in detail?

Thanks

like image 884
Grey Avatar asked May 30 '12 19:05

Grey


2 Answers

If the value is small enough, it is simply assigned. Otherwise it is assigned in an implementation-defined fashion. Typically this means it will "wrap around".

6.3.1.3-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.

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.

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.

like image 154
cnicutar Avatar answered Oct 22 '22 19:10

cnicutar


a is converted to the type of b as if by assignment.

(C99, 6.5.2.2p7) "If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type."

In your case, if the value to be converted can be represented in the new type, it is left unchanged.

(C99, 6.3.1.3p1) "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."

otherwise it is converted in an implementation defined manner:

(C99, 6.3.1.3p3) "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."

like image 43
ouah Avatar answered Oct 22 '22 20:10

ouah