Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can parentheses in C change the result type of operands of a bitwise operation?

I have fed the following code through a static analysis tool:

u1 = (u1 ^ u2); // OK

u1 = (u1 ^ u2) & u3;  // NOT OK

u1 = (u1 ^ u2) & 10; // NOT OK

u1 = (u1 ^ u2) & 10U; // NOT OK

u1 = (unsigned char)(u1 ^ u2) & 10U; // OK

u1 = (unsigned char)(u1 ^ u2) & u3;  // OK

"OK" means the static analysis tool did not complain. "NOT OK" means the static analysis tool did complain -- claiming that some operand of a bitwise operation is not an unsigned integer.

The results from the last 2 lines show that the parentheses are causing either

a. an actual type conversion to signed

b. something that the static analysis tool thinks is a type conversion to signed

I will ask the static analysis tool developer about (b).

But before I do, I would like to know if perhaps the C language is known to do (a)?

like image 314
talkaboutquality Avatar asked Sep 13 '11 10:09

talkaboutquality


People also ask

Why do we use bitwise operators in C++?

In this tutorial, we will learn about bitwise operators in C++ with the help of examples. In C++, bitwise operators perform operations on integer data at the individual bit-level. These operations include testing, setting, or shifting the actual bits.

What is the operator used to make 1's One's compliment & Bitwise and operator Bitwise or operator Bitwise negate operator a bitwise exclusive or?

3) What is the operator used to make 1's One's compliment.? Explanation: One's complement is created by Negate Operator ~. 00010110 is changed to 11101001 after applying ~ operator.


2 Answers

Nothing in C is done below int: eg when adding two unsigned chars, even before the addition, the operands are converted to int according to the default promotions.

unsigned char u1, u2, u3;
u1 = 0;
u2 = 42;
u3 = u1 + u2;

In the last line, first u1 and u2 are converted to int, then the + operator is applied to obtain a int value and then that value is converted back to unsigned char (of course the compiler can use shortcuts!)

like image 167
pmg Avatar answered Sep 19 '22 17:09

pmg


This is because, in C, the resulting type of an operation on two unsigned char:s is int. The static analysis tool correctly (though not very intuitive) reports that the & is applied to an int.

like image 36
Lindydancer Avatar answered Sep 20 '22 17:09

Lindydancer