0% found this document useful (0 votes)
2 views25 pages

C Notes

The document discusses various concepts in C programming, including variable declaration, constants, data types, and type conversions. It highlights the importance of keywords, identifiers, and user-defined types, as well as the rules governing their usage. Additionally, it covers implicit type conversion and the hierarchy of data types in expressions.

Uploaded by

pallavir2407
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

C Notes

The document discusses various concepts in C programming, including variable declaration, constants, data types, and type conversions. It highlights the importance of keywords, identifiers, and user-defined types, as well as the rules governing their usage. Additionally, it covers implicit type conversion and the hierarchy of data types in expressions.

Uploaded by

pallavir2407
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

fF defere sublace all he ceuances

Q#ncudetoio.h ud

Value cam be staed win ahosoiaxy blok and bu many bytey


ileocual conypilatioa procLd stod.
9lvaxisble is aasmed memou loealien dnat ian stau value
In odex to we vaiable dla proqxasner nust oeclaxe,specihy
type Lame

LHS RHS
b
(3i mDiAC)

Lad to pufpom zyraboud alue alhtnitwill complete am ereudiou Typiealy avetiys value o
Oibxoyi Calleeton o pre tu tode hat Cam be usd to
pezlaim comng task aodped up dualopmed.
9psiakf CHellauenld')

ist mai

pintfhello lwld ");


stonstat vnlue to te funetiou Callex. Sousce Code
hello.c

0he it ndicates dhot tenaim() netwms an


enpamded sees code
Compiler
CAstmbler
maehin code ar oljeet code (ello,o)

int mainO hello. ee

RAM
pisdf ([Link] "); he willitn Ar ello waulokautput

Oonpile
)bsembler Couesuon yecifahom
(inken
Hilude<stdio,h Gnveon charecb:
jot nain()
evel

lgenexal-pupose pxecedual- arieted, ltis tiutuetu Snaelie


PreLudable qust. ta Cwe have tu types o commersts -sissle line temns
-Plti line commsut tor bUescOne tas preblesn

-/'

ALGOLashi

LadktionalC 1972 Dennia Aichie


Conpiler tagnJtut itha pze pxasAd ende (eyaudlkl eode) une
1928.y Koiglia Dene lidie
ANST C 1284 tanot \ ANST omiter

[Link] Cowiter
)ltonpil timtinibiolyation a úoi able
[Link], losigued, uslgned Hiselude<stale.h>

Lintn 3
i t n=2
int nn = 8
ntns =
int Aug =(nLt n34 y4 us)/5;

Jeanf L)i asather waygiaisg valuey to uasindes is te


genrnd ingut unetiou ainilable to is wey dimdan in
Siepl stant

teeisaddueu ol apvata

#uinclue<stde.h
Couneclo wbtuewer flouchard
ptsd we we Connectar

Splal uedia fowcand ouclad


Symbals nome use

Atart
Temival
lestt sep)

Example asqueutdal Paochat

Decison ittepreuit Sum hltn2n3


oleiuicn pad
Deciica based cperalia
Aa
OpRKalar tell the tpilen to pen<asum cextais mathtmatial ar

kaupulate data oud la vaiabeu


gperatan
felational

decneneut perahr
dttienl
less ta

<stdlo.s geater Haau egual to


Mat egual to

gezla)
ee
anesed when e t toeut mene perator
0ical opeataA Ranling

Lelt to Rigld

at liute oill salue() as t has tagleat preeioleue

falss false
falie false

LLOHdttio aitey hot ill uat be eualuaedi Cate

false
falie
fale alse b20
false
Dd nat evaluate

fale
Iycituimaut Deetmt spumala
Iucremeut wnes eHeynnt taevalie waniable by

IacKemet()
wiU uant,eualuat

Qne-ine pstdee

oeted by
1
Mens poand

Lvalue
Rvalue
Lvalue s, alwoyys a otable ,
Frepresutr slany
tocatlbm
Rualue ds aslgn tu Lvalue.

decnendthe valu.
6

pnecioete++
-batth

sdubstlutoy 13

Ealntiom

Aignanet
pest-ie post-de

a (p(a=19)

ElQ4Xa 19

YOR (A)
ooooo100

(1oin3)

Bisue XOR^

at ist Conbtut
binany form.

MOw (owpt te iato. biany


valueto hetadeeimal
O DDD

(oooo) ( 8421)
Lwe
se tae famla
Davable kita to be slwftog
Q=15 b=6 c =0

mew oeel hit from


aiable )Hexe the eousitin ia bcalean Coypneslon hat esut

foruudls te ton clitiay is folse, eapuesion 2is ealuated


dis called as onvasy peralbe

32 16 8

ia s s tnow do its coupliment (nat)


tiuay prstou
>ineudle stdo.h

Coioliioal apexatauk lso Called Texinany sperato


pit(utr valua)

Tue
Sole
1aleplaoo 3
UNIT

eicutedaeuesealy

situalins ohere we e noy lave clange the rolek

Rind af deeision sakug la see thelan'a panbeular

sblemnln
staleea
>pt stotemet

Atatyt t alw ie tompiler lo eualole

Bue

folse
Sytax

tadle to he ereted a i nueusaÜG.

tonditon)
->incluae < stdo.
itain l) iata
else
iut pite,te, bill j
elebeck

bill>500)
Wj jner else Bock

else loddex hoitox mulliga lecisig


LAbtenut.

W/outer elie ock


i Black

t a

eley(aso)

pxitC' diuiate by i)}


tlse /ese block
Suwich stale meut has a bull in yrull way

che anahen way To snplint else- adden.

Callesslwe

Case ualue cant


Suith (eapnesiam /oniable) be stg, ate

break
hlocle
bHeak'

blok-n
oxeak

deoul Salewd
bneake,.
jnttaicej
choieR)";
Ylaiee);
ASOTE he bueak stattut iswwecd to end
Casci
statemetE
AOT E() wthaut bueak staeneut the praskaua
Case
Lcoutinue to the Met tse, exeeuting the cases Latil

ANOT E ) The decut ctatmit isexeuted uo


Case 3i
stotemut s Gptinal.

bxeak'

auinl"Eatex alphabet ");


Crse 'A:

breake
Caset:
puitf ('vauwet") ;

pant
hveale
pidt ("buwel")jtake

breake #incule <stoie.u


Casei

bneak'

byeak
Case0

break,
Case 1:
Hepeaf a block c Code undil thé xpeihed condition
nt ni, y claice' M. A logp atote ment alow proxammex to egeeute tae
attemut th gxoup c statem sut muliple fusnd wtlaut
Cocde.

hene ote ainly tuo typu a lop in C


ci) Ety Coitraledlocp

Laaitl (plaica)

bxeak'
Case

oe 3
program using the trigraphs ??( and ?2). ?? tilde

C ToKENS
Ina passage of text, individual words and punctuation
smallest individual units are known as C tokens. C hasmarks
six
are called tokens. Similarly, in a C program the
are written using these tokens and the syntax types of tokens as shown in Fig. 3.1. C programs
of the language.

CTOKENS

Keywords Constants Strings Operators


float -15.5 "ABC" +
while 100 "year"

Identifiers Special Symbols


main
amount

Fig. 3.1 Ctokens and examples


KEYwORDS AND IDENTIFIERS
Every C word is classified as either a keyword or an identifier. Allkeywords have fixed meanings and these
meanings cannot be changed. Keywords serve as basic building blocks for program statements. The list of all
keywords of ANSI C are listed in Table 3.3. All keywords must be written in lowercase. Some compilers may
use additional keywords that must be identified from the C manual.

Note c99 adds some more keywords. See the Appendix "C99 Features".

Identifiers refer to the names of variables, functions and arrays.)These are user-defined names and consist
of a sequence of letters and digits, with a letter as afirst character. Both uppercase and lowercase letters
are permitted, although lowercase letters are commonly used. The underscore character is also permitted in
identifiers. It is usually used as a link between two words in long identifiers.
Programming in ANSI C
49 struct
ANSI C Keyword int
Table 3.3 double switch
auto long typedef
else
break register
enum union
case return
extern unsigned
char short
float void
const signed
for volatile
Continue
sizeof
goto while
default static
if
do

Rules for ldentifiers


underscore).
an alphabet (or
1. First character must be
letters, digits or underscore.
2. Must consist of only
significant.
3. Only first 31 characters are
4. Cannot use a keyword.
5. Must not contain white space

CONSTANTS
change during the execution
Constants in C refer to fixed values that do not LO 3.2
of constants as illustrated in Fig. 3.2. Describe constants and
of a program. C supports several types
variables
Integer Constants
three types of integers, namely, decimal integer,
An integer constant refers to a sequence of digits. There are
octal integer and hexadecimal integer.
+ sign. Valid examples
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional - or
of decimal integer constants are:
123 321 0 654321 +78

CONSTANTS

Numeric constants Character constants

Integer Real Single character String


constants constants constants Constants

Fig. 3.2 Basic types of Cconstants


Embedded spaces, commas, and non-digit characters are not
permitted between digits. For exa
15 750 20,000 $1000
are illegal numbers.
Constants, Variables and Data Types 51 -
Similarly, floating point constants, by default represent double type data. If we want the resulting data type
to be float or long double, we must append the letter f or F to the number for float and letter Ior Lfor long
double as shown below:
Literal Type Value
0. double 0.0
0 double 0.0
12.0 double 12.0
1.234 double 1.234
-1.2f float -1.2
1.23456789L long double 1.23456789

User-Defined Type Declaration


Csuppots a feature known as type definition" that allows users to define an identifier that would represent
an existing data type. The user-defined data type identifier can later be used to declare variables. It takes the
general form:

typedef type identifier;


where type refers to an existing data type and "identifier" refers to the "new" name given to the data type.
The existing data type may belong to any class of type, including the user-defined ones. Remenber that the
new type is 'new only in name, but not the data type. typedef cannot create a new type. Some examples of
type definition are:
typedef int units;
typedef float marks;
Here, units symbolizes int and marks symbolizes float. They can be later used to declare variables as
follows:
units batchl, batch2;
marks namel [50], name2 [50];
batch1 and batch2 are inclared as int variable and name1[50] and name2[50] are declared as 50 element
floating point array variables. The main advantage of typedef is that we can create meaningful data type
names for increasing the readability of the program.
Another user-defined data type is enumerated data type provided by ANSlstandard. It is defined as follows:
enum identifier (value1, value2, .. valuen;
The "identifier" is a user-defined enumerated data type which can be used to declare variables that can have
one of the values enclosed within the braces (known as enumeration constants). After this definition, we can
declare variables to be of this 'new type as below:
enum identifier v1, v2, ... Vn
The enumerated variables v1, v2, ... Vn can only have one of the values value1, value2, .. valuen. The
assignments of the following types are valid:
v1 = val ue3;
v5 = valuel;
An example:
enum day {Monday, Tuesday, .. Sunday}:
enum day week st, week end;
Programming in AN'SIC
84 Operators and Expressions 85
EXPRESsIONS 7. else, if one of the operands is unsigned int, the other will be
IYPE CONVERSIONS IN will be unsigned int.
converted to unsigned int and the result
LO 4.4
Implicit Type Conversion Explain type conversions Conversion Hierarchy
variables of different types in an expression. in expressions Note that, C uses the rule that, in all expressions except assignments, any implicit type
Cpermits mbxing of constantsand proper type so that the conversions are made
intermediate values to the from a lower size type to a higher size type as shown below:
Cautomatically converts any significance. This automatic
without loosing any
expression can be evaluated
type conversion. types
conversion is known as implicit the operands are of different long double
strict rules of type conversion. If operation proceeds. The result is o
During evaluation it adheres to very higher' type before the
converted to the
the lower' type is automaticallyconversion process is illustrated in Fig. 4.8. double
the higher type. A typical type
float
X Conversion
int
unsigned long int
float
double
f:
Hierarchy
long int 1: long int
1/i unsigned int
long float int

long float short char

float Note that some versions of C automatically convert all floating-point operands to
float The final result of an expression is converted to the type of the variable on the leftdouble precision.
of the assignment sign
double before assigning the value to it. However, the following changes are introduced during the final assignment.
double
int
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
Fig. 4.8 Process of implicit type conversion 3. long int to int causes dropping of the excess higher order bits.
evaluating expressions.
Given below is the sequence of rules that are applied while
Allshort and char are automatically converted to int; then Explicit Conversion
converted to long double and the result will be
1. if one of the operands is long double, the other will be We have just discussed how C performs type conversion automatically. However. there are
instances when
iong double; we want to force a type conversion in a way that is different from the automatic conversion.) Consider, for
be converted to double and the result will be example, the calculation of ratio of females to males in a town.
2. else, if one of the operands is double, the other will
double; ratio = female number/male number
to float and the result will be float Since female number and male number are declared as integers in the program, the decimal part of the
3. else, if one of the operands is float, the other will be converted
unsigned long int and result of the division would be lost and ratio would represent a wrong figure. This problem can be solved
4. else, if one of the operands is unsigned long int, the other will be converted to by
the result will be unsigned long int; converting locally one of the variables to the floating point as shown below:
5. else, if one of the operands is long int and the other is unsigned int, then ratio = (float) female number/male_number
The operator (float) converts the female _number to floating point for the purpose of evaluation of the
(a) if unsigned int can be converted to long int, the unsigned int operand will be converted as such
and the result will be long int;
expression. Then using the rule of automatic conversion, the division is performed in floating point mode, thus
retaining the fractional part of result.
(b) else, both operands wil be converted to unsigned long int and the result will be unsigned long (Note that in no way does the operator (float) affect the value of the variable female number. And also, the
int; type of female number remains as int in the other parts of the program.
6. else, if one of the operands is long int, the other willbe converted to long int and the result will be long (The process of such a local conversion is known as explicit conversion or casting a value> The general
int: form of a cast is:
4.9 Use ota cast

OPERATOR PRECEDENCE AND ASSOCIATIVITY


As mentioned earlier each operator,
in C has a precedence associated with it.
This precedence is used to determine how LO 4.5
an
one operator is evaluated. There are distinctexpression involving more than Discuss how operator
operator may belong to one of these levels. Thelevels of precedence and an precedence and
of precedence are evaluated first. The operators at the higher level
operators of the same precedence are associativity rules are
evaluated either from left to right' or from 'right to left', applied
This is known as the associativity property of an depending on the level.
operator. Table
acomplete list of operators, their precedence levels, and their 4.8 provides
rules of association. The groups are listed in
Table 4.8 Summary of COperators
Operator Description Associativity Rank
Function call Left to right 1
Aray element reference
Unary plus
Unary minus Right to left 2
++ Increment
Decrement
Logical negation
Ones complement
Pointer reference (indirection)
& Address
sÍzeof Size of an object
(ype) Type cast (conversion)
Multiplication Left to right
Division
% Modulus
(Contd.)
88 Programming in ANSIC
Addition Left to right
Subtraction
Left shift Left to right 5
>> Right shift
Less than Left to right 6

Less than or equal to


Greater than
Greater than or equal to
Equality Left to right 7

Inequality
& Bitwise AND Left to right
Bitwise XOR Left to right
Bitwise OR Left to right 10
&& Logical AND Left to right 11
Logical OR Left to right 12
2: Conditional expression Right to left 13
Assignment operators Right to left 14
*=|%=
+== &=

<<=>>=

Comma operator Left to right 15

the order of decreasing precedence. Rank 1 indicates the highest precedence level and 15 the lowest.
also includes those operators,which we have not yet been discussed.
It is very important to note carefully, the order of precedence and associativity of operators. Consi
following conditional statement:
if (x == 10+15 && y<10)
The precedence rules say that the addition operator has a higher priority than the logical operator (&
the relational operators (== and<). Therefore, the addition of 10and 15 is executed first. This is egu
to:
if (x==25 && y < 10)
The next step is to determine whether x is equal to 25 and y is less than 10. If we assume a valu
for x and 5 for y, then
x == 25 is FALSE (0)
y<10 is TRUE (1)
Note that since the operator <enjoys a higher priority compared to = y<10 is tested first and the
25 is tested,
Finally we get:
if (FALSE && TRUE)
Because one of the conditions is FALSE, the complex condition is FALSE.
In the case of &&, it is guaranteed that the second operand will not be evaluated if the first is Ze
the case of |l, the second operand will not be evaluated if the first is non-zero.
Rules of Precedence and Associativity
" Precedence rules decides the order in which different operators are applied operator
area
" Associativity rule decides the order in which multiple occurrences of the same level

You might also like