Sie sind auf Seite 1von 8

Operators in C

C programs consist of statements, and most statements are composed of expressions and operators

Expressions:-represents a single data items, such as number or a character. The expression may consist of a single entity, such as a
constant, a variable, an array element or reference to a function. a+b,x=y
Statements:- A statement causes the computer to carry out some action. 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 . There are three
different classes of statements in C. They are expression statements, compound statement and control statement.
An expression statement consists of an expression followed by a semicolon.
A compound statement consists of several individual statements enclosed within a pair of braces { }.
Control statements are used to create special program features, such a logical tests, loops and branches.

White Space

The term white space refers to spaces, tabs, and blank lines in your source code. The C compiler isn't sensitive to white space. When
the compiler reads a statement in your 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;

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

Unary operators:-that act upon a single operand to produce a new value


Binary operators:- act upon a two operand to produce a new value.
Ternary:- act upon three operand to produce a new value

. Arithmetic operators
C supports the arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulo remainder
% may not be used with reals

C provides a modulo or remainder after dividing by operator. When dividing floating point numbers there isnt a remainder, just a
fraction. Hence this operator cannot be applied to real.

. Using Arithmetic Operators

Int i=5,j=4,k;
Double f=5.2,g=4.2,h;

@
k=i/j
h=f/g
h=i/j

there are different kinds of integer.


Need for many different + variations, numerous combinations of int and double short etc.
+ operator choose itself what sort of addition to perform, if + sees an integer on its left and its right integer addition is
performed. The compiler examines the types on either side of each operator and does whatever is appropriate compiler is
only concerned with the types of the operands.
No account whatever is taken of the type being assigned to h=i/j it is the type of I and j cause integer division to be
performed the fact that the result is being assigned to h a double has no influence at all.

. The Cast operator

Operands that differ in type may undergo type conversion before the expression takes on its final value. In general the final result
will be expressed in the highest precision possible, consistent with the data types of the operands.

The cast operator temporarily change the type of a variable

Int i=5,j=4;
Double f;
F=(double) i/j;
F=i/(double)j;
F=(double)i/(double)j;
F=(double)(i/j);

If either operand is a double the other is automatically prompted


Integer division is done the result 1 is changes to double 1.00000
The cast operator temporarily changes the type of the variable/expression it is applies. Rather it is the value of the
expression that undergoes type conversion wherever the cast appears.

Int I=7,x;
Float f=8.5;
X=(I+f)%4
Is invalid, because the first operand (I+f) is floating point rather then integer.
((int)(I+f))%4
Forces the first operand to be an integer and is therefore valid.

. Increment and decrement

C has two special operators for adding and subtracting one form a variable
++,--
These may be either prefix(before the variable) or postfix(after the variable).

Prefix postfix
Int i.j=5;
I=++j;
Printf(I=%d,j=%d\n,I,j);
J=5;
I=j++;
Printf(I=%d,j=%d\n,I,j);

I=6,j=6
I=5,j=6

Prefix:- When the prefix operators are used the increment or decrement happens first the changed value is then assigned.
The current value of j is changed and become 6 the 6 is copied across the = into the variable i.

@
Postfix:-With the postfix operators the increment or decrement happens second. The unchanged value is assigned then the
value changed

Int a=2,b=3;
Int c;
C=++a-b--;
Printf(a=%d,b=%d,c=%d\na,b,c)
A=3,b=2,c=0

. Truth in C
To understand Cs comparison operators and logical operators it is important to understand how C regards truth.
There is no Boolean data type in C, integers are used instead
The value of 0 or 0.0 is false.
Any other value , 1,-1.0.3 is ture
True:-Any non zero value is true False:- Any zero value is false

Testing truth:- Load the value to be tested into a register and see if any of its bits are set, if even a single bit is set, the value is
immediately identified as true. If no bit is set anywhere, the value is identifies as false.
Comparison operators
< less than
<= less then or equal to
> greater than
>= greater than or equal to
== is equal to
!= is not equal to
These all give 1 when the comparison succeeds and 0when the comparison fails

. Logical operators
&& and
|| or
! not
Evaluation is left to right
Evaluation is short circuit

If(I<10&&a>0)
I<10 is evaluated first if false the whole statement is false a>0 would not be evaluated.
Truth table
False true &&
F t f
F t t
||
f t f
t t f

Remember to use parentheses with conditions,

Give a=3,b=4,c=2 which is the result of following logical expressions


(a<--b)&&(a==c)
(3<--4)&&(3==2)
(3<3)&&(3==2)
0&&0
0

@
. Bitwise operators

C programs can store information in individual bits or groups of bits. File access permissions are a common example. The bitwise
operators allow you to manipulate individual bits in a byte or in a larger data unit: you can clear, set, or invert any bit or group of
bits. You can also shift the bit pattern of an integer to the left or right.

The bit pattern of an integer type consists of bit positions numbered from right to left, beginning with position 0 for the least
significant bit. For example, consider the char value '*', which in ASCII encoding is equal to 42, or binary 101010:

Bit pattern Bit positions

0 7

0 6

1 5

0 4

1 3

0 2

1 1

0 0

In this example, the value 101010 is shown in the context of an 8-bit byte; hence the two leading zeros.

Bit operators may only be applied to integer types


& bitwise and
| bitwise inclusive or
^ bitwise exclusive or
~ ones compliment
>> right shift
<< left shift
As bk dr needed to manipulate hardware registers in their pdp-11 they needed the proper tools

Or 0 1 and 0 1 xor 0 1
0 0 1 0 0 0 0 0 1
1 1 1 1 0 1 1 1 0

the ones compliment operator~ flips all the bits in a value so all 1s are turned to 0s are turned to 1s.

Expression (or declaration) Bit pattern

int a = 6; 0 ... 0 0 1 1 0

@
Expression (or declaration) Bit pattern

int b = 11; 0 ... 0 1 0 1 1

a & b 0 ... 0 0 0 1 0

a | b 0 ... 0 1 1 1 1

a ^ b 0 ... 0 1 1 0 1

~a

short a=0xbeb9;
short b=0x5d27;
unsigned short c=7097;
printf(0x%x,a&b);
printf(0x%x,a|b);
printf(0x%x,a^b);
printf(%u,,c<<2);
printf(%u\n,c>>1);

Shift operators

The shift operators transpose the bit pattern of the left operand by the number of bit positions indicated by the
right operand.

Operator Meaning Example Result

<< Shift left x << y Each bit value in x is moved y positions to the left.

>> Shift right x >> y Each bit value in x is moved y positions to the right.
The operands of the shift operators must be integers. Before the actual bit-shift, the integer promotions are performed on both
operands. The value of the right operand must not be negative, and must be less than the width of the left operand after integer
promotion.
unsigned long n = 0xB, // Bit pattern: 0 ... 0 0 0 1 0 1 1
result = 0;
result = n << 2; // 0 ... 0 1 0 1 1 0 0
result = n >> 2; // 0 ... 0 0 0 0 0 1 0

c<<2 multiplies the number by 4 shifting one place left multiplies by 2, shifting two places multiplies by 4.
Shifting right by one divides the number by 2.
. Assignment
An assigned value is always made available for subsequent use.
Int I,j,k,l,m,n;
I=j=k=l=m=n=22;
Printf(%I\n,j=93);

@
Whenever a value is assigned in c the assigned value is left lying around in a handy register, this value in the register may
then be referred to subsequently, or merely overwritten by the next statement .
One of the most frequent mistake is to confuse test for equlity ==, with assignment=
. Other assignment operator
In each of these
Expression1 op=expression2
Is equivalent to
(expression1)=(expression1)op(expression2)

A=a+2 can be written as a+=2


. Sizeof operator

Determine how many byes a variable occupies. The sizeof operator yields the size of its operand in bytes. Programs need to
know the size of objects mainly in order to reserve memory for them dynamically, or to store binary data in files.


Long bit;
Printf(\big\is %u bytes\n,sizeof(big));
Printf(a short is %u bytes\nsizeof(short));
Printf(a double is %u bytes\n,sizeof double);

Sizeof(double) and sizeof double are equivalent. Is NOT a standard library function.

. Conditional Expression operator


The conditional expression operator provides an in-line/then/else
If the first expression is true the second is evaluated
If the first expression is false and third is evaluated
Int I,j=100,k=-1;
I=(j>k)? j:k

If(j>k)
I=j
Else
I=k
C provides a rather terse (brief) , ternary operator (i.e. one which takes 3 operands) as an alternative to the if then else
construct .
Condition ? value when true : value when false
The types of the two expression must be the same. It wouldnt make much sense to have one expression evaluating to a
double while the other evaluates to an unsigned char

Int a=10,b=15,x
X=(a<b)?++a;++b;
Printf(x=%d,a=%d,b=%d\n,x,a,b);

X=11,a=11,b=16

. Comma operators

The comma operator is a binary operator:

expression 1 , expression 2

The comma operator ensures sequential processing: first the left operand is evaluated, then the right operand. The result of the
complete expression has the type and value of the right operand.

@
X=(y=2,y-1)
First assigns y the value 2 and then x the value1.

The comma operator has the lowest precedence of all operators.


Generally, comma operator is used in the for loop.

. Precedence of Operators
C treats operators with different importance known as precedence
There are 15 levels.
In general the unary operators have higher precedence then binary operators.
The natural precedence of operations can be altered through the use of parentheses. Parentheses can always be used to
improve clarity.
int a=42,b=2,c=2,d=5;
printf("mini char=%i\n",a-b/c*d); /* a-[(b/c)*d] */
printf("max char=%i",(a-b)/(c*d));

Int j=3*4+48/7;
Printf(j=%I\n,j);

. Associativily of operators
For two operators of equal precedence (i.e. same importance) a second rule associability is used.
Associativity is either left to right (left operator first) or right to left

Int I=6*4/7;
Printf(I=%d\n,i);
I=3

Review
Int I=0,j,k=7,m=5,n;
J=m+=2;
Printf(j=%d\n,j);
J=k++>7;
Prinf(j=%d\n,j);
J=I==0&k;
Printf(j=%d\n,j);
N=!I>k>>2;
Printf(n=%d\n,n);

. Exercise .
1. Write a program in sum.c, which reads two integers and prints out the sum, the difference and the product. Divide them
too, printing your answer to two decimal places. Also print the remainder after the two numbers are divided.

Introduce a test to ensure that when dividing the number the second number is not zero.

What happens when you add two numbers and the sum is too large to fit into the data type.
2. Cut and past sum.c code into bitop.c . This should also read two integers but print the result of betwise anding , bitwise
oring and bitwise exclusive oring. Then either use these two integers or prompt for two more and print the first left shifted
by the second and first right shifted by the second. Choose whether to output any of these results as decimal hexadecimal
or octal.

What happens when a number is left shifted by zero? If a number is left shifted by-1 does that mean it is right shifted by 1?
3. Write a program in a file call vol.c which uses the area code form area.c. In addition to the radius it prompts for a height
with which it calculates the volume of a cylinder, the formula is volume=area*height.

@
@

Das könnte Ihnen auch gefallen