Saturday, June 11, 2016

Use of Parenthesis in Expression

At the time of writing down the expression, use parentheses in an expression you want to execute first. For example, consider the following example of expression:

int a = 3, b = 4;
int result = a + b * 2

This expression will initially multiplying b with 2, then add to the value of a. This is because the operator * has a higher priority than the + operator. Through this kind of writing, the above expression would return the value 11. However, if you want the sum of a and b executed first, and then multiplied by 2, you should have to use parentheses, as shown below.

int result = (a + b) * 2

Through this kind of writing, the above expression would yield a value of 14.

1 comment: