User manual

mikroC PRO for dsPIC
MikroElektronika
245
Logical vs. Bitwise
Be aware of the principle difference between how bitwise and logical operators work. For example:
0222222 & 0555555 /* equals 000000 */
0222222 && 0555555 /* equals 1 */
~ 0x1234 /* equals 0xEDCB */
! 0x1234 /* equals 0 */
Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C. Syntax of the conditional operator is:
expression1 ? expression2 : expression3
The expression1 is evaluated rst. If its value is true, then expression2 evaluates and expression3 is ignored.
If expression1 evaluates to false, then expression3 evaluates and expression2 is ignored. The result will be a
value of either expression2 or expression3 depending upon which of them evaluates.
Conditional operator associates from right to left.
Note: The fact that only one of these two expressions evaluates is very important if they are expected to produce side effects!
Here are a couple of practical examples:
/* Find max(a, b): */
max = ( a > b ) ? a : b;
/* Convert small letter to capital: */
/* (no parentheses are actually necessary) */
c = ( c >= ‘a’ && c <= ‘z’ ) ? ( c - 32 ) : c;
Conditional Operator Rules
expression1 must be a scalar expression; expression2 and expression3 must obey one of the following rules:
1. Both expressions have to be of arithmetic type. expression2 and expression3 are subject to usual
arithmetic conversions, which determines the resulting type.
2. Both expressions have to be of compatible struct or union types. The resulting type is a structure or
union type of expression2 and expression3.
3. Both expressions have to be of void type. The resulting type is void.
4. Both expressions have to be of type pointer to qualied or unqualied versions of compatible types.
The resulting type is a pointer to a type qualied with all type qualiers of the types pointed to by both
expressions.
5. One expression is a pointer, and the other is a null pointer constant. The resulting type is a pointer to a
type qualied with all type qualiers of the types pointed to by both expressions.
6. One expression is a pointer to an object or incomplete type, and the other is a pointer to a qualied or
unqualied version of void. The resulting type is that of the non-pointer-to-void expression.