Search This Blog

Saturday, May 26, 2012

Statements, Expressions, and Operators


Statements, Expressions, and Operators
 
            C programs consist of statements, and most statements are composed of
expressions and operators. We need to understand these three topics in order to
be able to write C programs.
Statements
            A statement is a complete direction instructing the computer to carry out some task. In C, statements are usually written one per line, although some statements span multiple lines. C statements always end with a semicolon (except for preprocessor directives such as #define and #include.
For example:        x = 2 + 3;
is an assignment statement. It instructs the computer to add 2 and 3 and to assign the result to the variable x.

Statements and White Space
            The term white space refers to spaces, tabs, and blank lines in the source code. The C compiler isn't sensitive to white space. When the compiler reads a statement in the source code, it looks for the characters in the statement and for the terminating semicolon, but it ignores white space. Thus, the statement
     x=2+3;
is equivalent to this statement:
     x = 2 + 3;
It is also equivalent to this:
x        =
2
+
3;

This gives us a great deal of flexibility in formatting our source code. We shouldn't use formatting like the previous example, however. Statements should be entered one per line with a standardized scheme for spacing around variables and operators.  The point is to keep our source code readable.
However, the rule that C doesn't care about white space has one exception: Within literal string constants, tabs and spaces aren't ignored; they are considered part of the string. A string is a series of characters. Literal string constants are strings that are enclosed within quotes and interpreted literally by the compiler, space for space. Although it's extremely bad form, the following is legal:
printf(
"Hello, world!"
);

This, however, is not legal:
printf("Hello,
world!");

To break a literal string constant line, you must use the backslash character
(\) just before the break. Thus, the following is legal:
printf("Hello,\
world!");

Null Statements
If we place a semicolon by itself on a line, we create a null statement i.e. a statement that doesn't perform any action. This is perfectly legal in C. Later
  Eg,  the null statement is:            ;
Compound Statements
A compound statement, also called a block, is a group of two or more C statements
enclosed in braces. Here's an example of a block:
{
    printf("Hello, ");
    printf("world!");
}

In C, a block can be used anywhere a single statement can be used. Note that the enclosing braces can be positioned in different ways. The following is equivalent to the preceding
example:
{printf("Hello, ");
printf("world!");}

It's a good idea to place braces on their own lines, making the beginning and end of blocks clearly visible. Placing braces on their own lines also makes it easier to see whether we've left one out. But if  there are large number of statements inside the block , it is not possible to place braces in one lines.
Notes:
·         DO put block braces on their own lines. This makes the code easier to read.
·         DO line up block braces so that it's easy to find the beginning and end of a
      block.
·         DON'T spread a single statement across multiple lines if there's no need to do
      so. Limit statements to one line if possible.



Expressions
In C, an expression is anything that evaluates to a numeric value. C expressions come in all levels of complexity.
Simple Expressions
The simplest C expression consists of a single item: a simple variable, literal
constant, or symbolic constant. Here are four expressions:
      Expression                        Description
      PI                          A symbolic constant (defined in the program)
      20                          A literal constant
      rate                                    A variable
      -1.25                      Another literal constant

A literal constant evaluates to its own value. A symbolic constant evaluates to the value it was given when we created it using the #define directive. A variable evaluates to the current value assigned to it by the program.
Complex Expressions
Complex expressions consist of simpler expressions connected by operators.
For example:
2 + 8
is an expression consisting of the sub-expressions 2 and 8 and the addition operator +. The expression 2 + 8 evaluates 10. we  can also write C expressions of great complexity:

1.25 / 8 + 5 * rate + rate * rate / cost

Consider the following statement:
x = a + 10;
            This statement evaluates the expression a + 10 and assigns the result to x. In addition, the entire statement x = a + 10 is itself an expression that evaluates to the value of the variable on the left side of the equal sign.
Thus, we can write statements such as the following, which assigns the value of the expression
a + 10 to both variables, x and y as:
y = x = a + 10;
We can also write statements such as this:
x = 6 + (y = 4 + 5);
 All of these are complex expression.
Operators
An operator is a symbol that instructs C to perform some operation, or action, on one or more operands. An operand is something that an operator acts on. In C, all operands are expressions. C operators fall into several categories:
·         The assignment operator
·         Mathematical operators
·         Relational operators
·         Logical operators
·         Conditional operators
·         Special operator
·         Cast operator
·         Bitwise operator
The Assignment Operator
The assignment operator is the equal sign (=). Its use in programming is somewhat different from its use in regular math. If we write
x = y;
in a C program, it doesn't mean "x is equal to y." Instead, it means "assign the value of y to x." In a C assignment statement, the right side can be any expression, and the left side must be a variable name. Thus, the form is as follows:
variable = expression;
When executed, expression is evaluated, and the resulting value is assigned to variable.


Mathematical Operators
C's mathematical operators perform mathematical operations such as addition and subtraction. C has two unary mathematical operators and five binary mathematical operators.
Unary Mathematical Operators
The unary mathematical operators are so named because they take a single operand. C has two unary mathematical operators
Table : C's unary mathematical operators.
      Operator
Symbol
Action
Examples
      Increment
++
Increments the operand by one
++x, x++
      Decrement
--
Decrements the operand by one
--x, x--

The increment and decrement operators can be used only with variables, not with constants. The operation performed is to add one to or subtract one from the operand. In other words, the statements
++x; --y;
are the equivalent of these statements:
x = x + 1;    y = y - 1;
We  should note from above Table that either unary operator can be placed before its operand (prefix mode) or after its operand (postfix mode). These two modes are not equivalent. They differ in terms of when the increment or decrement is performed:  When used in prefix mode, the increment and decrement operators modify their   operand before it's used.   When used in postfix mode, the increment and decrement operators modify their   operand after it's used.
For example : Consider following statements:
x = 10;
y = x++;
After these statements are executed, x has the value 11, and y has the value 10. The value of x was assigned to y, and then x was incremented. In contrast, the following statements result in both y and x having the value 11. x is incremented, and then its value is assigned to y.
x = 10;
y = ++x;

 illustrates the difference between prefix mode and postfix mode increment.
  /* Demonstrates unary operator prefix and postfix modes */
  #include <stdio.h>
  int a, b;
  main()
  {
      /* Set a and b both equal to 5 */
      a = b = 5;
      /* Print them, decrementing each time. */
      /* Use prefix mode for b, postfix mode for a */
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d\n", a--, --b);
   return 0;
}
output:
5    4
4    3
3    2
2    1
1    0
ANALYSIS: This program declares two variables, a and b, the variables are set to the value of 5. With the execution of each printf() statement , both a and b are decremented by 1. a is decremented after it  is printed,whereas b is decremented before it is printed.

Binary Mathematical Operators
C's binary operators take two operands. The binary operators, which include the common mathematical operations
Table  C's binary mathematical operators.
      Operator
Symbol
Action
Example
      Addition
+
Adds two operands
x + y
      Subtraction
-
Subtracts the second operand from the first operand
x - y
      Multiplication
*
Multiplies two operands
x * y
      Division
/
Divides the first operand by the second operand
x / y
      Modulus
%
Gives the remainder when the first operand is divided by the second operand
x % y

The first four operators listed in Table  should be familiar to us in general mathematics. The fifth operator, modulus operator  returns the remainder when the first operand is divided by the second operand. For example, 11 modulus 4 equals 3 . Here are some more examples:
100 %9 equals 1          10 %5 equals 0            40 % 6 equals 4

An example to illustrate the  modulus operator to convert a large number of seconds into hours, minutes, and seconds.
   /* Inputs a number of seconds, and converts to hours, minutes, and seconds. */

#include <stdio.h>
                                        /* Define constants */
#define SECS_PER_MIN 60
#define SECS_PER_HOUR 3600

unsigned int seconds, minutes, hours, secs_left, mins_left;

main()
{
          /* Input the number of seconds */
  printf("Enter number of seconds (< 65000): ");
  scanf("%d", &seconds);

  hours = seconds / SECS_PER_HOUR;
  minutes = seconds / SECS_PER_MIN;
  mins_left = minutes % SECS_PER_MIN;
  secs_left = seconds % SECS_PER_MIN;
  printf("%u seconds is equal to ", seconds);
  printf("%u h, %u m, and %u s\n", hours, mins_left,secs_left);

  return 0;
}
Enter number of seconds (< 65000): 60
60 seconds is equal to 0 h, 1 m, and 0 s
Enter number of seconds (< 65000): 10000
10000 seconds is equal to 2 h, 46 m, and 40 s

Operator Precedence and Parentheses
In an expression that contains more than one operator, then the precedence plays the important role for evaluation. Precedence is the  order in which operations are performed.
e.g. x = 4 + 5 * 3;
Performing the addition first results in the following, and x is assigned the value 27:
x = 9 * 3;
 if the multiplication is performed first,  x is assigned the value 19:
x = 4 + 15;

So  some rules are needed about the order in which operations are performed. This order, called operator precedence, is strictly spelled out in C. Each operator has a specific precedence. When an expression is evaluated, operators with higher precedence are performed first. Following Table lists the precedence of C's mathematical operators. Number 1 is the highest precedence and
thus is evaluated first.
Table : The precedence of C's mathematical operators.
      Operators
Relative Precedence
      ++          --
1
      *    /    %
2
      +     -
3

So  in any C expression, operations are performed in the following order:
  Unary increment and decrement
  Multiplication, division, and modulus
  Addition and subtraction
If an expression contains more than one operator with the same precedence level, the operators are performed in left-to-right order as they appear in the expression. For example, in the following expression, the % and * have the same precedence level, but the % is the leftmost operator, so it is performed first:
12 % 5 * 2
A sub-expression enclosed in parentheses is evaluated first, without regard to operator precedence. Thus, you could write
x = (4 + 5) * 3;

The expression 4 + 5 inside parentheses is evaluated first, so the value assigned to x is 27.
We can use multiple and nested parentheses in an expression. When parentheses are nested, evaluation proceeds from the innermost expression outward. Look at the following complex expression:
x = 25 - (2 * (10 + (8 / 2)));
The evaluation of this expression proceeds as follows:
  1. The innermost expression, 8 / 2, is evaluated first, yielding the value 4: 25 - (2 * (10 + 4))
  2. Moving outward, the next expression, 10 + 4, is evaluated, yielding the   value 14: 25 - (2 * 14)
  3. The last, or outermost, expression, 2 * 14, is evaluated, yielding the   value 28: 25 - 28
  4. The final expression, 25 - 28, is evaluated, assigning the value -3 to the   variable x: x = -3

Order of Subexpression Evaluation
C expressions contain more than one operator with the same precedence level, they are evaluated left to right. For example, in the expression
w * x / y * z
w is multiplied by x, the result of the multiplication is then divided by y, and the result of the division is then multiplied by z.
Look at this expression: and try to understand the order of evaluation
w * x / y + z / y
w * x / ++y + z / y
Notes:
·         DO use parentheses to make the order of expression evaluation clear.
·         DON'T overload an expression. It is often more clear to break an expression into two or more statements. This is especially true when you're using the unary operators (--) or (++).

Relational Operators
C's relational operators are used to compare expressions, asking questions such as, "Is x greater than 100?" or "Is y equal to 0?" An expression containing a relational operator evaluates to either true (1) or false (0). .
Table  C's relational operators.
Operator
Symbol
Question Asked
Example
      Equal
==
Is operand 1 equal to operand 2?
x == y
      Greater than
> 
Is operand 1 greater than operand 2?
x > y
      Less than
< 
Is operand 1 less than operand 2?
x < y
      Greater than or equal to
>=
Is operand 1 greater than or equal to operand 2?
x >= y
      Less than or equal to
<=
Is operand 1 less than or equal to operand 2?
x <= y
      Not equal
!=
Is operand 1 not equal to operand 2?
x != y

Table: Relational operators in use.
      Expression
How It Reads
What It Evaluates To
      5 == 1
Is 5 equal to 1?
0 (false)
      5 > 1
Is 5 greater than 1?
1 (true)
      5 != 1
Is 5 not equal to 1?
1 (true)
      (5 + 10) == (3 * 5)
Is (5 + 10) equal to (3 * 5)?
1 (true)




The if Statement(Conditional Statements)
Relational operators are used mainly to construct the relational expressions used in if and while statements. Consider the basics of the if statement to show how relational operators are used to make program control statements.
In its basic form, the if statement evaluates an expression and directs program execution depending on the result of that evaluation. The form of an if statement is as follows:
if (expression)
    statement;
If expression evaluates to true, statement is executed. If expression evaluates to false, statement is not executed. In either case, execution then passes to whatever code follows the if statement. We can say that execution of statement depends on the result of expression. Both the line if (expression) and the line statement; are considered to comprise the complete if statement; they are not separate statements. An if statement can control the execution of multiple statements through the use of a compound statement, or block. A block can be used anywhere a single statement can be used. Therefore, We can write an if statement as follows:
if (expression)
{
    statement1;
    statement2;
    /* additional code goes here */
    statementn;
}

 An if statement should always end with the conditional statement that follows it. In the following, statement1 executes whether or not x equals 2, because each  line is evaluated as a separate statement, not together as intended:
if( x == 2);          /* semicolon does not belong!  */
statement1;

   An example to demonstrate the use of if statements

   #include <stdio.h>

   int x, y;

   main()
   {
       /* Input the two values to be tested */

      printf("\nInput an integer value for x: ");
      scanf("%d", &x);
      printf("\nInput an integer value for y: ");
      scanf("%d", &y);

      /* Test values and print result */

      if (x == y)
          printf("x is equal to y\n");

      if (x > y)
          printf("x is greater than y\n");

      if (x < y)
          printf("x is smaller than y\n");

      return 0;
  }
Input an integer value for x: 100
Input an integer value for y: 10
x is greater than y
Input an integer value for x: 10
Input an integer value for y: 100
x is smaller than y
Input an integer value for x: 10
Input an integer value for y: 10
x is equal to y

The else Clause
An if statement can optionally include an else clause. The else clause is included as follows:
if (expression)
    statement1;
else
    statement2;

If expression evaluates to true, statement1 is executed. If expression evaluates to false, statement2 is executed. Both statement1 and statement2 can be compound statements or blocks.
An example to demonstrates the use of if statement with else clause

   #include <stdio.h>

   int x, y;

   main()
   {
       /* Input the two values to be tested */

      printf("\nInput an integer value for x: ");
      scanf("%d", &x);
      printf("\nInput an integer value for y: ");
      scanf("%d", &y);

      /* Test values and print result */

      if (x == y)
          printf("x is equal to y\n");
      else
          if (x > y)
              printf("x is greater than y\n");
          else
              printf("x is smaller than y\n");

      return 0;
  }
Input an integer value for x: 99
Input an integer value for y: 8
x is greater than y
Input an integer value for x: 8
Input an integer value for y: 99
x is smaller than y
Input an integer value for x: 99
Input an integer value for y: 99
x is equal to y

The if Statement
Form 1
if( expression )
    statement1;
next_statement;
This is the if statement in its simplest form. If expression is true, statement1 is executed. If expression is not true, statement1 is ignored. And next statement is executed.
Form 2
if( expression )
    statement1;
else
    statement2;
next_statement;
This is the most common form of the if statement. If expression is true, statement1 is executed; otherwise, statement2 is executed.
Form 3
if( expression1 )
    statement1;
else if( expression2 )
    statement2;
else
    statement3;
next_statement;

This is a nested if. If the first expression, expression1, is true, statement1 is executed before the program continues with the next_statement. If the first expression is not true, the second expression, expression2, is checked. If the first expression is not true, and the second is true, statement2 is executed. If both expressions are false, statement3 is executed. . There may be any no of such if statements Only one of the them statements is executed before next statement.
Example 1
if( salary > 45,0000 )
    tax = 0.30*salary;
else
    tax = 0.25*salary;

Example 2
if( age < 13 )
    printf("Child");
else if( age <=19 )
    printf("Teen");
else if(age<65)
    printf(“Adult”);
else
    printf( "Senior Citizen");

Evaluating Relational Expressions
 Relational expressions evaluate to a value of either false (0) or true (1). Although the most common use of relational expressions is within if statements and other conditional constructions, they can be used as purely numeric values.
An example: Demonstrates the evaluation of relational expressions

   #include <stdio.h>
   int a;
   main()
   {
       a = (5 == 5);                 /* Evaluates to 1 */
      printf("\na = (5 == 5) evaluates a = %d", a);

      a = (5 != 5);                 /* Evaluates to 0 */
      printf("\na = (5 != 5) evaluatesa = %d", a);

      a = (12 == 12) + (5 != 1); /* Evaluates to 1 + 1 */
      printf("\na = (12 == 12) + (5 != 1) evaluates a = %d\n", a);
      return 0;
  }
a = (5 == 5) evaluates  a = 1
a = (5 != 5) evaluates a = 0
a = (12 == 12) + (5 != 1)  evaluates a = 2


The Precedence of Relational Operators
Like the mathematical operators, the relational operators each have a precedence that determines the order in which they are performed in a multiple-operator expression. Similarly, We can use parentheses to modify precedence in expressions that use relational operators.
First, all the relational operators have a lower precedence than the mathematical operators. Thus, if we write the following, 2 is added to x, and the result is compared to y:
if (x + 2 > y)
This is the equivalent of the following line, which is a good example of using parentheses for the sake of clarity:
if ((x + 2) > y)
Although they aren't required by the C compiler, the parentheses surrounding (x + 2) make it clear that it is the sum of x and 2 that is to be compared with y.
There is also a two-level precedence within the relational operators, as shown
in Table below:
Table : The order of precedence of C's relational operators.
      Operators
Relative Precedence
      < <= > >=
1
      != ==
2

Thus, if we write            x == y > z
it is the same as           x == (y > z)  because C first evaluates the expression y > z, resulting in a value of 0 or 1. Next, C determines whether x is equal to the 1 or 0 obtained in the first step.

Note:
·         DON'T put assignment statements in if statements.
·         DON'T use the "not equal to" operator (!=) in an if statement containing an else. It's almost always clearer to use the "equal to" operator (==) with an        else. For instance, the following code:
if ( x != 5 )
   statement1;
else
   statement2;

  would be better written as this:
if (x == 5 )
   statement2;
else
   statement1;
Logical Operators
Sometimes we need to ask more than one relational question at once.  C's logical operators let us combine two or more relational expressions into a single expression that evaluates to either true or false. .
Table  C's logical operators.
      Operator
Symbol
Example
      AND
&&
exp1 && exp2 e.g. ( num>100)&&(num%2==0)
      OR
||
exp1 || exp2           e.g. (num<100)||(num%2!=0)
      NOT
!
!exp1        e.g. num!=5


  C's logical operators in use.
      Expression
What It Evaluates To
      (exp1 && exp2)
True (1) only if both exp1 and exp2 are true; false (0) otherwise
      (exp1 || exp2)
True (1) if either exp1 or exp2 is true; false (0) only if both are false
      (!exp1)
False (0) if exp1 is true; true (1) if exp1 is false

We  can see that expressions that use the logical operators evaluate to either true or false, depending on the true/false value of their operand(s). Following Table shows some actual code examples.
Table  Code examples of C's logical operators.
      Expression
What It Evaluates To
      (5 == 5) && (6 != 2)
True (1), because both operands are true
      (5 > 1) || (6 < 1)
True (1), because one operand is true
      (2 == 1) && (5 == 5)
False (0), because one operand is false
      !(5 == 4)
True (1), because the operand is false

We can create expressions that use multiple logical operators. For example, to ask the question "Is x equal to 2, 3, or 4?"  We write
(x == 2) || (x == 3) || (x == 4)

The logical operators often provide more than one way to ask a question. If x is an integer variable, the preceding question also could be written in either of the following ways:
(x > 1) && (x < 5)
(x >= 2) && (x <= 4)

More on True/False Values
C's relational expressions evaluate to 0 to represent false and to 1 to represent true,however,  any numeric value is interpreted as either true or false when it is used in a C expression or statement that is expecting a logical value (that is, a true or false value).
The rules are as follows:
·         A value of zero represents false.
·         Any nonzero value represents true.
This is illustrated by the following example, in which the value of x is printed:
x = 125;
if (x)
   printf("%d", x);    /*   prints 125 */
Because x has a nonzero value, the if statement interprets the expression (x) as true. You can further generalize this because, for any C expression, writing
if(expression)
is equivalent to writing
if(expression != 0)
Both evaluate to true if expression is nonzero and to false if expression is 0. Using the not (!) operator, we can also write
if(!expression)
which is equivalent to
if(expression == 0)

The Precedence of Operators
The ! operator has a precedence equal to the unary mathematical operators ++ and --. Thus, ! has a higher precedence than all the relational operators and all the binary mathematical operators.
In contrast, the && and || operators have much lower precedence, lower than all the mathematical and relational operators, although && has a higher precedence than ||.
 As with all of C's operators, parentheses can be used to modify the evaluation order when using the logical operators. Consider the following example:
We want to write a logical expression that makes three individual comparisons:
  1. Is a less than b?
  2. Is a less than c?
  3. Is c less than d?
we want the entire logical expression to evaluate to true if condition 3 is true and if either condition 1 or condition 2 is true. You might write
a < b || a < c && c < d
However, this won't do what we  intended. Because the && operator has higher precedence than ||, the expression is equivalent to
a < b || (a < c && c < d)
and evaluates to true if (a < b) is true or both a<c and c<d are true. So we need to write
(a < b || a < c) && c < d
which forces the || to be evaluated before the &&.
An example to demostrate Logical operator precedence.
   #include <stdio.h>

   /* Initialize variables. Note that c is not less than d, */
   /* which is one of the conditions to test for. */
   /* Therefore, the entire expression should evaluate as false.*/

   int a = 5, b = 6, c = 5, d = 1;
   int x;
  main()
  {
      /* Evaluate the expression without parentheses */
      x = a < b || a < c && c < d;
      printf("\nWithout parentheses the expression evaluates as %d", x);
      /* Evaluate the expression with parentheses */
     x = (a < b || a < c) && c < d;
      printf("\nWith parentheses the expression evaluates as %d\n", x);
      return 0;
  }
Without parentheses the expression evaluates as 1
With parentheses the expression evaluates as 0


Compound Assignment Operators
C's compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation. For example, if we want to increase the value of x by 5, or, in other words, add 5 to x and assign the result to x. we can write
x = x + 5;
Using a compound assignment operator, which you can think of as a shorthand method of assignment, we can write
x += 5;
In more general notation, the compound assignment operators have the following syntax (where op represents a binary operator):
exp1 op= exp2
This is equivalent to writing
exp1 = exp1 op exp2;
We can create compound assignment operators using the five binary mathematical operators defined before.
Table : Examples of compound assignment operators.
      When we Write This.
It Is Equivalent To This
      x *= y
x = x * y
      y -= z + 1
y = y - z + 1
      a /= b
a = a / b
      x += y / 8
x = x + y / 8
      y %= 3
y = y % 3


The Conditional Operator
The conditional operator is C's only ternary operator, meaning that it takes three operands. Its syntax is
exp1 ? exp2 : exp3;
If exp1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. If exp1 evaluates to false (that is, zero), the entire expression evaluates as the value of exp3. For example, the following statement
assigns the value 1 to x if exp is true and assigns 100 to x if exp  is false:
x = exp ? 1 : 100;
Likewise, to make z equal to the larger of x and y, we can write
z = (x > y) ? x : y;

Conditional operator functions somewhat like an if statement. The preceding statement could also be written like this:
 if(exp)x = 1; else x=100;
and
if (x > y)
z = x;
else
z = y;

The conditional operator can't be used in all situations in place of an if...else construction, but the conditional operator is more concise. The conditional operator can also be used in places you can't use an if statement, such as inside a single printf() statement:
printf( "The larger value is %d", ((x > y) ? x : y) );

Special Operator: The Comma Operator
The comma is frequently used in C as a simple punctuation mark, serving to separate variable declarations, function arguments, and so on. In certain situations, the comma acts as an operator rather than just as a separator. We can form an expression by separating two sub-expressions with a comma. The result is as follows:
             Both expressions are evaluated, with the left expression being evaluated first.The entire expression evaluates to the value of the right expression.
For example, the following statement assigns the value of b to x, then increments a, and then increments b:
x = (a++ , b++);

Because the ++ operator is used in postfix mode, the value of b,before it is incremented,is assigned to x. Using parentheses is necessary because the comma operator has low precedence, even lower than the assignment operator. The use of comma operator is used in for looping construct as:
 for(n=1,m=10;n<=m;n++,n++)

exchanging values:  t = x,x = y,y = t;

     The other types of special operators used in C are pointer operators(&,*), member operators(.and ->),function operator (), array operator []etc.

The Cast operator:
            C supports another type of operator for data conversion. The cast operator are used to type cast for the data. Once a data are defined as one type and need to convert in to another during calculation rather changing the actual value of the variable , we need to cast operators.
The cast operator is nothing but just the type keyboard of the dada type as int,float,double etc.
The syntax for type casting is
(type-name)expression
 where type-name is one of the C data type. The expression may be constant, variable or any expression. Some example of casts and their action are shown in table below
Table: to show the use of cast operator:
Example
Action
x = (int)7.5
7.5 is converted to integer by truncation
a = (int)21/(int)4.5
Evaluates as 21/4 result is 5
b = (float)sum/n
Division is done in floating point mode
y = (int)(a+b)
The result of a+b is converted in to integer
c=(char)87
returns the character whose ASCII code is 87



Bitwise Operators:
C has special  operators for bit oriented programming known as bitwise operators. They are used for manipulating data in bit level. These are used to testing the bits or shifting the bits left or right.
Bitwise operators are not applied to float and double. Following table shows the bitwise operators and their meanings.
Table: Bitwise operator
Operator
Meaning
&
bitwise AND
|
bitwise OR
^
bitwise X-OR
<< 
shift left
>> 
shift right
~
one’s complement

No comments:

Post a Comment