C Quick Guide
C Quick Guide
CQuickGuide
CQuickGuide
Advertisements
PreviousPage
NextPage
CLanguageOverview
C is a generalpurpose, highlevel language that was
originally developed by Dennis M. Ritchie to develop the
UNIXoperatingsystematBellLabs.Cwasoriginallyfirst
implementedontheDECPDP11computerin1972.
In1978,BrianKernighanandDennisRitchieproducedthe
firstpubliclyavailabledescriptionofC,nowknownasthe
K&Rstandard.
The UNIX operating system, the C compiler, and
essentially all UNIX application programs have been
written in C. C has now become a widely used
professionallanguageforvariousreasons
Easytolearn
Structuredlanguage
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
1/145
6/3/2016
CQuickGuide
Itproducesefficientprograms
Itcanhandlelowlevelactivities
Itcanbecompiledonavarietyofcomputerplatforms
FactsaboutC
Cwasinventedtowriteanoperatingsystemcalled
UNIX.
CisasuccessorofBlanguagewhichwasintroduced
aroundtheearly1970s.
Thelanguagewasformalizedin1988bythe
AmericanNationalStandardInstitute(ANSI).
TheUNIXOSwastotallywritteninC.
TodayCisthemostwidelyusedandpopularSystem
ProgrammingLanguage.
Mostofthestateoftheartsoftwarehavebeen
implementedusingC.
Today'smostpopularLinuxOSandRDBMSMySQL
havebeenwritteninC.
WhyuseC?
C was initially used for system development work,
particularly the programs that makeup the operating
system. C was adopted as a system development
language because it produces code that runs nearly as
fast as the code written in assembly language. Some
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
2/145
6/3/2016
CQuickGuide
examplesoftheuseofCmightbe
OperatingSystems
LanguageCompilers
Assemblers
TextEditors
PrintSpoolers
NetworkDrivers
ModernPrograms
Databases
LanguageInterpreters
Utilities
CPrograms
ACprogramcanvaryfrom3linestomillionsoflinesand
it should be written into one or more text files with
extension ".c" for example, hello.c. You can use "vi",
"vim" or any other text editor to write your C program
intoafile.
Thistutorialassumesthatyouknowhowtoeditatextfile
andhowtowritesourcecodeinsideaprogramfile.
CEnvironmentSetup
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
3/145
6/3/2016
CQuickGuide
TryitOptionOnline
We have set up the C Programming
environmentonline,sothatyoucancompile
and execute all the available examples on
line.Itgivesyouconfidenceinwhatyouare
reading and enables you to verify the
programs with different options. Feel free to
modifyanyexampleandexecuteitonline.
Try the following example using our online
compileravailableatCodingGround.
#include<stdio.h>
intmain(){
/*myfirstprograminC*/
printf("Hello,World!\n");
return0;
}
LocalEnvironmentSetup
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
4/145
6/3/2016
CQuickGuide
TextEditor
Thiswillbeusedtotypeyourprogram.Examplesoffewa
editors include Windows Notepad, OS Edit command,
Brief,Epsilon,EMACS,andvimorvi.
Thenameandversionoftexteditorscanvaryondifferent
operatingsystems.Forexample,Notepadwillbeusedon
Windows,andvimorvicanbeusedonwindowsaswell
asonLinuxorUNIX.
Thefilesyoucreatewithyoureditorarecalledthesource
files and they contain the program source codes. The
source files for C programs are typically named with the
extension".c".
Before starting your programming, make sure you have
onetexteditorinplaceandyouhaveenoughexperience
towriteacomputerprogram,saveitinafile,compileit
andfinallyexecuteit.
TheCCompiler
The source code written in source file is the human
readable source for your program. It needs to be
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
5/145
6/3/2016
CQuickGuide
"compiled",intomachinelanguagesothatyourCPUcan
actually execute the program as per the instructions
given.
The compiler compiles the source codes into final
executableprograms.Themostfrequentlyusedandfree
availablecompileristheGNUC/C++compiler,otherwise
you can have compilers either from HP or Solaris if you
havetherespectiveoperatingsystems.
ThefollowingsectionexplainshowtoinstallGNUC/C++
compiler on various OS. We keep mentioning C/C++
togetherbecauseGNUgcccompilerworksforbothCand
C++programminglanguages.
InstallationonUNIX/Linux
IfyouareusingLinuxorUNIX,thencheckwhetherGCC
is installed on your system by entering the following
commandfromthecommandline
$gccv
IfyouhaveGNUcompilerinstalledonyourmachine,then
itshouldprintamessageasfollows
Usingbuiltinspecs.
Target:i386redhatlinux
Configuredwith:../configureprefix=/usr.......
Threadmodel:posix
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
6/145
6/3/2016
CQuickGuide
gccversion4.1.220080704(RedHat4.1.246)
InstallationonMacOS
IfyouuseMacOSX,theeasiestwaytoobtainGCCisto
download the Xcode development environment from
Apple's web site and follow the simple installation
instructions.OnceyouhaveXcodesetup,youwillbeable
touseGNUcompilerforC/C++.
Xcode
is
currently
available
developer.apple.com/technologies/tools/
at
InstallationonWindows
ToinstallGCConWindows,youneedtoinstallMinGW.To
install
MinGW,
www.mingw.org
go
to
the
MinGW
homepage,
7/145
6/3/2016
CQuickGuide
gcccore,gccg++,binutils,andtheMinGWruntime,but
youmaywishtoinstallmore.
Add the bin subdirectory of your MinGW installation to
yourPATHenvironmentvariable,sothatyoucanspecify
thesetoolsonthecommandlinebytheirsimplenames.
After the installation is complete, you will be able to run
gcc, g++, ar, ranlib, dlltool, and several other GNU tools
fromtheWindowscommandline.
CProgramStructure
Before we study the basic building blocks of the C
programminglanguage,letuslookatabareminimumC
programstructuresothatwecantakeitasareferencein
theupcomingchapters.
HelloWorldExample
ACprogrambasicallyconsistsofthefollowingparts
PreprocessorCommands
Functions
Variables
Statements&Expressions
Comments
8/145
6/3/2016
CQuickGuide
#include<stdio.h>
intmain(){
/*myfirstprograminC*/
printf("Hello,World!\n");
return0;
}
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
9/145
6/3/2016
CQuickGuide
CompileandExecuteCProgram
Letusseehowtosavethesourcecodeinafile,andhow
tocompileandrunit.Followingarethesimplesteps
Openatexteditorandaddtheabovementioned
code.
Savethefileashello.c
Openacommandpromptandgotothedirectory
whereyouhavesavedthefile.
Typegcc hello.c and press enter to compile your
code.
Iftherearenoerrorsinyourcode,thecommand
prompt will take you to the next line and would
generatea.outexecutablefile.
Now,typea.outtoexecuteyourprogram.
You will see the output "Hello World" printed on
thescreen.
$gcchello.c
$./a.out
Hello,World!
Makesurethegcccompilerisinyourpathandthatyou
are running it in the directory containing the source file
hello.c.
CBasicSyntax
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
10/145
6/3/2016
CQuickGuide
CBasicSyntax
You have seen the basic structure of a C program, so it
will be easy to understand other basic building blocks of
theCprogramminglanguage.
TokensinC
A C program consists of various tokens and a token is
eitherakeyword,anidentifier,aconstant,astringliteral,
or a symbol. For example, the following C statement
consistsoffivetokens
printf("Hello,World!\n");
Theindividualtokensare
printf
(
"Hello,World!\n"
)
;
Semicolons
InaCprogram,thesemicolonisastatementterminator.
That is, each individual statement must be ended with a
semicolon.Itindicatestheendofonelogicalentity.
Givenbelowaretwodifferentstatements
printf("Hello,World!\n");
return0;
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
11/145
6/3/2016
CQuickGuide
Comments
Comments are like helping text in your C program and
theyareignoredbythecompiler.Theystartwith/*and
terminatewiththecharacters*/asshownbelow
/*myfirstprograminC*/
Youcannothavecommentswithincommentsandtheydo
notoccurwithinastringorcharacterliterals.
Identifiers
A C identifier is a name used to identify a variable,
function, or any other userdefined item. An identifier
starts with a letter A to Z, a to z, or an underscore '_'
followedbyzeroormoreletters,underscores,anddigits
(0to9).
C does not allow punctuation characters such as @, $,
and % within identifiers. C is a casesensitive
programming language. Thus, Manpower and manpower
aretwodifferentidentifiersinC.Herearesomeexamples
ofacceptableidentifiers
mohdzaraabcmove_namea_123
myname50_tempja23b9retVal
Keywords
The following list shows the reserved words in C. These
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
12/145
6/3/2016
CQuickGuide
else
long
switch
break
enum
register
typedef
case
extern
return
union
char
float
short
unsigned
const
for
signed
void
continue
goto
sizeof
volatile
default
if
static
while
do
int
struct
_Packed
double
WhitespaceinC
A line containing only whitespace, possibly with a
comment, is known as a blank line, and a C compiler
totallyignoresit.
WhitespaceisthetermusedinCtodescribeblanks,tabs,
newlinecharactersandcomments.Whitespaceseparates
one part of a statement from another and enables the
compiler to identify where one element in a statement,
suchasint,endsandthenextelementbegins.Therefore,
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
13/145
6/3/2016
CQuickGuide
inthefollowingstatement
intage;
theremustbeatleastonewhitespacecharacter(usually
aspace)betweenintandageforthecompilertobeable
to distinguish them. On the other hand, in the following
statement
fruit=apples+oranges;//getthetotalfruit
nowhitespacecharactersarenecessarybetweenfruitand
=, or between = and apples, although you are free to
includesomeifyouwishtoincreasereadability.
CDataTypes
Data types in c refer to an extensive system used for
declaring variables or functions of different types. The
typeofavariabledetermineshowmuchspaceitoccupies
instorageandhowthebitpatternstoredisinterpreted.
ThetypesinCcanbeclassifiedasfollows
S.N.
1
Types&Description
BasicTypes
They are arithmetic types and are further
classifiedinto:(a)integertypesand(b)floating
pointtypes.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
14/145
6/3/2016
CQuickGuide
Enumeratedtypes
They are again arithmetic types and they are
used to define variables that can only assign
certain discrete integer values throughout the
program.
Thetypevoid
Thetypespecifiervoidindicatesthatnovalueis
available.
Derivedtypes
They include (a) Pointer types, (b) Array types,
(c) Structure types, (d) Union types and (e)
Functiontypes.
IntegerTypes
The following table provides the details of standard
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
15/145
6/3/2016
CQuickGuide
integertypeswiththeirstoragesizesandvalueranges
Type
Storage
size
Valuerange
char
1byte
128to127or0to255
unsigned
char
1byte
0to255
signed
char
1byte
128to127
int
2or4
bytes
32,768to32,767or
2,147,483,648to2,147,483,647
unsigned
int
2or4
bytes
0to65,535or0to4,294,967,295
short
2bytes
32,768to32,767
unsigned
short
2bytes
0to65,535
long
4bytes
2,147,483,648to2,147,483,647
unsigned
long
4bytes
0to4,294,967,295
16/145
6/3/2016
CQuickGuide
thesizeofinttypeonanymachine
#include<stdio.h>
#include<limits.h>
intmain(){
printf("Storagesizeforint:%d\n",sizeof(int));
return0;
}
FloatingPointTypes
The following table provide the details of standard
floatingpoint types with storage sizes and value ranges
andtheirprecision
Type
Storage
size
Valuerange
Precision
float
4byte
1.2E38to
3.4E+38
6decimal
places
double
8byte
2.3E308to
1.7E+308
15decimal
places
long
double
10byte
3.4E4932to
1.1E+4932
19decimal
places
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
17/145
6/3/2016
CQuickGuide
return0;
}
ThevoidType
The void type specifies that no value is available. It is
usedinthreekindsofsituations
S.N.
Types&Description
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
18/145
6/3/2016
CQuickGuide
Functionreturnsasvoid
There are various functions in C which do not
returnanyvalueoryoucansaytheyreturnvoid.
A function with no return value has the return
type as void. For example, void exit (int
status)
Functionargumentsasvoid
There are various functions in C which do not
accept any parameter. A function with no
parameter can accept a void. For example, int
rand(void)
Pointerstovoid
A pointer of type void * represents the address
of an object, but not its type. For example, a
memory allocation function void *malloc(
size_t size ) returns a pointer to void which
canbecastedtoanydatatype.
CVariables
Avariableisnothingbutanamegiventoastoragearea
thatourprogramscanmanipulate.EachvariableinChas
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
19/145
6/3/2016
CQuickGuide
Description
char
Typicallyasingleoctet(onebyte).Thisisan
integertype.
int
Themostnaturalsizeofintegerforthe
machine.
float
Asingleprecisionfloatingpointvalue.
double
Adoubleprecisionfloatingpointvalue.
void
Representstheabsenceoftype.
20/145
6/3/2016
CQuickGuide
VariableDefinitioninC
A variable definition tells the compiler where and how
much storage to create for the variable. A variable
definitionspecifiesadatatypeandcontainsalistofone
ormorevariablesofthattypeasfollows
typevariable_list;
Thelineinti,j,kdeclaresanddefinesthevariablesi,j,
and k which instruct the compiler to create variables
namedi,jandkoftypeint.
Variables can be initialized (assigned an initial value) in
their declaration. The initializer consists of an equal sign
followedbyaconstantexpressionasfollows
typevariable_name=value;
Someexamplesare
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
21/145
6/3/2016
CQuickGuide
externintd=3,f=5;//declarationofdandf.
intd=3,f=5;//definitionandinitializingdandf.
bytez=22;//definitionandinitializesz.
charx='x';//thevariablexhasthevalue'x'.
VariableDeclarationinC
Avariabledeclarationprovidesassurancetothecompiler
thatthereexistsavariablewiththegiventypeandname
so that the compiler can proceed for further compilation
withoutrequiringthecompletedetailaboutthevariable.A
variable declaration has its meaning at the time of
compilation only, the compiler needs actual variable
declarationatthetimeoflinkingtheprogram.
A variable declaration is useful when you are using
multiple files and you define your variable in one of the
files which will be available at the time of linking of the
program. You will use the keyword extern to declare a
variableatanyplace.Thoughyoucandeclareavariable
multiple times in your C program, it can be defined only
onceinafile,afunction,orablockofcode.
Example
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
22/145
6/3/2016
CQuickGuide
/*actualinitialization*/
a=10;
b=20;
c=a+b;
printf("valueofc:%d\n",c);
f=70.0/3.0;
printf("valueoff:%f\n",f);
return0;
}
23/145
6/3/2016
CQuickGuide
youprovideafunctionnameatthetimeofitsdeclaration
and its actual definition can be given anywhere else. For
example
//functiondeclaration
intfunc();
intmain(){
//functioncall
inti=func();
}
//functiondefinition
intfunc(){
return0;
}
LvaluesandRvaluesinC
TherearetwokindsofexpressionsinC
lvalue Expressions that refer to a memory
locationarecalled"lvalue"expressions.Anlvalue
may appear as either the lefthand or righthand
sideofanassignment.
rvalue The term rvalue refers to a data value
that is stored at some address in memory. An
rvalueisanexpressionthatcannothaveavalue
assignedtoitwhichmeansanrvaluemayappear
on the righthand side but not on the lefthand
sideofanassignment.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
24/145
6/3/2016
CQuickGuide
Variablesarelvaluesandsotheymayappearontheleft
hand side of an assignment. Numeric literals are rvalues
and so they may not be assigned and cannot appear on
the lefthand side. Take a look at the following valid and
invalidstatements
intg=20;//validstatement
10=20;//invalidstatement;wouldgeneratecompiletimeerror
CConstants&Literals
Constantsrefertofixedvaluesthattheprogrammaynot
alter during its execution. These fixed values are also
calledliterals.
Constants can be of any of the basic data types like an
integer constant, a floating constant, a character
constant, or a string literal. There are enumeration
constantsaswell.
Constants are treated just like regular variables except
thattheirvaluescannotbemodifiedaftertheirdefinition.
IntegerLiterals
Anintegerliteralcanbeadecimal,octal,orhexadecimal
constant.Aprefixspecifiesthebaseorradix:0xor0Xfor
hexadecimal,0foroctal,andnothingfordecimal.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
25/145
6/3/2016
CQuickGuide
FloatingpointLiterals
A floatingpoint literal has an integer part, a decimal
point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or
exponentialform.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
26/145
6/3/2016
CQuickGuide
CharacterConstants
Character literals are enclosed in single quotes, e.g., 'x'
canbestoredinasimplevariableofchartype.
A character literal can be a plain character (e.g., 'x'), an
escapesequence(e.g.,'\t'),orauniversalcharacter(e.g.,
'\u02C0').
There are certain characters in C that represent special
meaning when preceded by a backslash for example,
newline(\n)ortab(\t).
Here,youhavealistofsuchescapesequence
codes
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
27/145
6/3/2016
CQuickGuide
Followingistheexampletoshowafewescapesequence
characters
#include<stdio.h>
intmain(){
printf("Hello\tWorld\n\n");
return0;
}
StringLiterals
Stringliteralsorconstantsareenclosedindoublequotes
"". A string contains characters that are similar to
character literals: plain characters, escape sequences,
anduniversalcharacters.
You can break a long line into multiple lines using string
literalsandseparatingthemusingwhitespaces.
Here are some examples of string literals. All the three
formsareidenticalstrings.
"hello,dear"
"hello,\
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
28/145
6/3/2016
CQuickGuide
dear"
"hello,""d""ear"
DefiningConstants
TherearetwosimplewaysinCtodefineconstants
Using#definepreprocessor.
Usingconstkeyword.
The#definePreprocessor
Given below is the form to use #define preprocessor to
defineaconstant
#defineidentifiervalue
Thefollowingexampleexplainsitindetail
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
29/145
6/3/2016
CQuickGuide
#include<stdio.h>
#defineLENGTH10
#defineWIDTH5
#defineNEWLINE'\n'
intmain(){
intarea;
area=LENGTH*WIDTH;
printf("valueofarea:%d",area);
printf("%c",NEWLINE);
return0;
}
TheconstKeyword
You can use const prefix to declare constants with a
specifictypeasfollows
consttypevariable=value;
Thefollowingexampleexplainsitindetail
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
30/145
6/3/2016
CQuickGuide
#include<stdio.h>
intmain(){
constintLENGTH=10;
constintWIDTH=5;
constcharNEWLINE='\n';
intarea;
area=LENGTH*WIDTH;
printf("valueofarea:%d",area);
printf("%c",NEWLINE);
return0;
}
CStorageClasses
Astorageclassdefinesthescope(visibility)andlifetime
of variables and/or functions within a C Program. They
precedethetypethattheymodify.Wehavefourdifferent
storageclassesinaCprogram
auto
register
static
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
31/145
6/3/2016
CQuickGuide
extern
TheautoStorageClass
Theautostorageclassisthedefaultstorageclassforall
localvariables.
{
intmount;
autointmonth;
}
TheregisterStorageClass
The register storage class is used to define local
variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size
equal to the register size (usually one word) and can't
have the unary '&' operator applied to it (as it does not
haveamemorylocation).
{
registerintmiles;
}
Theregistershouldonlybeusedforvariablesthatrequire
quick access such as counters. It should also be noted
that defining 'register' does not mean that the variable
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
32/145
6/3/2016
CQuickGuide
ThestaticStorageClass
Thestaticstorageclassinstructsthecompilertokeepa
local variable in existence during the lifetime of the
programinsteadofcreatinganddestroyingiteachtimeit
comes into and goes out of scope. Therefore, making
localvariablesstaticallowsthemtomaintaintheirvalues
betweenfunctioncalls.
The static modifier may also be applied to global
variables. When this is done, it causes that variable's
scopetoberestrictedtothefileinwhichitisdeclared.
In C programming, when static is used on a class data
member, it causes only one copy of that member to be
sharedbyalltheobjectsofitsclass.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
33/145
6/3/2016
CQuickGuide
#include<stdio.h>
/*functiondeclaration*/
voidfunc(void);
staticintcount=5;/*globalvariable*/
main(){
while(count){
func();
}
return0;
}
/*functiondefinition*/
voidfunc(void){
staticinti=5;/*localstaticvariable*/
i++;
printf("iis%dandcountis%d\n",i,count);
}
TheexternStorageClass
Theexternstorageclassisusedtogiveareferenceofa
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
34/145
6/3/2016
CQuickGuide
intcount;
externvoidwrite_extern();
main(){
count=5;
write_extern();
}
SecondFile:support.c
#include<stdio.h>
externintcount;
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
35/145
6/3/2016
CQuickGuide
voidwrite_extern(void){
printf("countis%d\n",count);
}
Here,externisbeingusedtodeclarecountinthesecond
file, where as it has its definition in the first file, main.c.
Now,compilethesetwofilesasfollows
$gccmain.csupport.c
COperators
Anoperatorisasymbolthattellsthecompilertoperform
specific mathematical or logical functions. C language is
richinbuiltinoperatorsandprovidesthefollowingtypes
ofoperators
ArithmeticOperators
RelationalOperators
LogicalOperators
BitwiseOperators
AssignmentOperators
MiscOperators
36/145
6/3/2016
CQuickGuide
works.
ArithmeticOperators
The following table shows all the arithmetic operators
supportedbytheClanguage.AssumevariableAholds10
andvariableBholds20then
ShowExamples
Operator
Description
Example
Addstwooperands.
A+B=30
Subtractssecondoperandfrom
thefirst.
AB=10
Multipliesbothoperands.
A*B=200
Dividesnumeratorbyde
numerator.
B/A=2
ModulusOperatorand
remainderofafteraninteger
division.
B%A=0
++
Incrementoperatorincreases
theintegervaluebyone.
A++=11
Decrementoperatordecreases
theintegervaluebyone.
A=9
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
37/145
6/3/2016
CQuickGuide
RelationalOperators
The following table shows all the relational operators
supportedbyC.AssumevariableAholds10andvariable
Bholds20then
ShowExamples
Operator
Description
Example
==
Checksifthevaluesoftwo
operandsareequalornot.If
yes,thenthecondition
becomestrue.
(A==B)is
nottrue.
!=
Checksifthevaluesoftwo
operandsareequalornot.If
thevaluesarenotequal,then
theconditionbecomestrue.
(A!=B)is
true.
>
Checksifthevalueofleft
operandisgreaterthanthe
valueofrightoperand.Ifyes,
thentheconditionbecomes
true.
(A>B)is
nottrue.
<
Checksifthevalueofleft
operandislessthanthevalue
ofrightoperand.Ifyes,then
theconditionbecomestrue.
(A<B)is
true.
>=
Checksifthevalueofleft
operandisgreaterthanor
(A>=B)is
nottrue.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
38/145
6/3/2016
CQuickGuide
equaltothevalueofright
operand.Ifyes,thenthe
conditionbecomestrue.
<=
Checksifthevalueofleft
operandislessthanorequalto
thevalueofrightoperand.If
yes,thenthecondition
becomestrue.
(A<=B)is
true.
LogicalOperators
Following table shows all the logical operators supported
byClanguage.AssumevariableAholds1andvariableB
holds0,then
ShowExamples
Operator
Description
Example
&&
CalledLogicalANDoperator.If
boththeoperandsarenon
zero,thenthecondition
becomestrue.
(A&&B)is
false.
||
CalledLogicalOROperator.If
anyofthetwooperandsisnon
zero,thenthecondition
becomestrue.
(A||B)is
true.
CalledLogicalNOTOperator.It
isusedtoreversethelogical
!(A&&B)is
true.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
39/145
6/3/2016
CQuickGuide
stateofitsoperand.Ifa
conditionistrue,thenLogical
NOToperatorwillmakeitfalse.
BitwiseOperators
Bitwise operator works on bits and perform bitbybit
operation.Thetruthtablesfor&,|,and^isasfollows
p
p&q
p|q
p^q
AssumeA=60andB=13inbinaryformat,theywillbe
asfollows
A=00111100
B=00001101
A&B=00001100
A|B=00111101
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
40/145
6/3/2016
CQuickGuide
A^B=00110001
~A=11000011
The following table lists the bitwise operators supported
byC.Assumevariable'A'holds60andvariable'B'holds
13,then
ShowExamples
Operator
Description
Example
&
BinaryANDOperatorcopiesa
bittotheresultifitexistsin
bothoperands.
(A&B)=
12,i.e.,
00001100
BinaryOROperatorcopiesabit
ifitexistsineitheroperand.
(A|B)=61,
i.e.,0011
1101
BinaryXOROperatorcopiesthe
bitifitissetinoneoperand
butnotboth.
(A^B)=
49,i.e.,
00110001
BinaryOnesComplement
Operatorisunaryandhasthe
effectof'flipping'bits.
(~A)=61,
i.e,.1100
0011in2's
complement
form.
<<
BinaryLeftShiftOperator.The
leftoperandsvalueismoved
leftbythenumberofbits
A<<2=
240i.e.,
11110000
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
41/145
6/3/2016
CQuickGuide
specifiedbytherightoperand.
>>
BinaryRightShiftOperator.
Theleftoperandsvalueis
movedrightbythenumberof
bitsspecifiedbytheright
operand.
A>>2=15
i.e.,0000
1111
AssignmentOperators
The following table lists the assignment operators
supportedbytheClanguage
ShowExamples
Operator
Description
Example
Simpleassignmentoperator.
Assignsvaluesfromrightside
operandstoleftsideoperand
C=A+B
willassign
thevalueof
A+BtoC
+=
AddANDassignmentoperator.
Itaddstherightoperandto
theleftoperandandassignthe
resulttotheleftoperand.
C+=Ais
equivalentto
C=C+A
SubtractANDassignment
operator.Itsubtractstheright
operandfromtheleftoperand
andassignstheresulttothe
leftoperand.
C=Ais
equivalentto
C=CA
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
42/145
6/3/2016
CQuickGuide
*=
MultiplyANDassignment
operator.Itmultipliestheright
operandwiththeleftoperand
andassignstheresulttothe
leftoperand.
C*=Ais
equivalentto
C=C*A
/=
DivideANDassignment
operator.Itdividestheleft
operandwiththerightoperand
andassignstheresulttothe
leftoperand.
C/=Ais
equivalentto
C=C/A
%=
ModulusANDassignment
operator.Ittakesmodulus
usingtwooperandsandassigns
theresulttotheleftoperand.
C%=Ais
equivalentto
C=C%A
<<=
LeftshiftANDassignment
operator.
C<<=2is
sameasC=
C<<2
>>=
RightshiftANDassignment
operator.
C>>=2is
sameasC=
C>>2
&=
BitwiseANDassignment
operator.
C&=2is
sameasC=
C&2
^=
BitwiseexclusiveORand
assignmentoperator.
C^=2is
sameasC=
C^2
|=
BitwiseinclusiveORand
C|=2is
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
43/145
6/3/2016
CQuickGuide
assignmentoperator.
sameasC=
C|2
MiscOperatorssizeof&ternary
Besides the operators discussed above, there are a few
other important operators including sizeof and ? :
supportedbytheCLanguage.
ShowExamples
Operator
Description
Example
sizeof()
Returnsthesizeofavariable.
sizeof(a),
whereais
integer,will
return4.
&
Returnstheaddressofa
variable.
&areturns
theactual
addressof
thevariable.
Pointertoavariable.
*a
?:
ConditionalExpression.
IfCondition
istrue?
thenvalueX
:otherwise
valueY
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
44/145
6/3/2016
CQuickGuide
OperatorsPrecedenceinC
Operatorprecedencedeterminesthegroupingoftermsin
an expression and decides how an expression is
evaluated.Certainoperatorshavehigherprecedencethan
others for example, the multiplication operator has a
higherprecedencethantheadditionoperator.
Forexample,x=7+3*2here,xisassigned13,not
20 because operator * has a higher precedence than +,
soitfirstgetsmultipliedwith3*2andthenaddsinto7.
Here, operators with the highest precedence appear at
thetopofthetable,thosewiththelowestappearatthe
bottom. Within an expression, higher precedence
operatorswillbeevaluatedfirst.
ShowExamples
Category
Operator
Associativity
Postfix
()[]>.++
Lefttoright
Unary
+!~++(type)*&
sizeof
Righttoleft
Multiplicative
*/%
Lefttoright
Additive
Lefttoright
Shift
<<>>
Lefttoright
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
45/145
6/3/2016
CQuickGuide
Relational
<<=>>=
Lefttoright
Equality
==!=
Lefttoright
BitwiseAND
&
Lefttoright
BitwiseXOR
Lefttoright
BitwiseOR
Lefttoright
LogicalAND
&&
Lefttoright
LogicalOR
||
Lefttoright
Conditional
?:
Righttoleft
Assignment
=+==*=/=%=>>=
<<=&=^=|=
Righttoleft
Comma
Lefttoright
CDecisionMaking
Decision making structures require that the programmer
specifiesoneormoreconditionstobeevaluatedortested
bytheprogram,alongwithastatementorstatementsto
beexecutediftheconditionisdeterminedtobetrue,and
optionally, other statements to be executed if the
conditionisdeterminedtobefalse.
Show below is the general form of a typical decision
making structure found in most of the programming
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
46/145
6/3/2016
CQuickGuide
languages
Statement&Description
ifstatement
followed
by
one
or
more
statements.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
47/145
6/3/2016
CQuickGuide
if...elsestatement
Anifstatementcanbefollowedbyanoptional
else statement, which executes when the
Booleanexpressionisfalse.
3
nestedifstatements
switchstatement
nestedswitchstatements
The?:Operator
We have covered conditional operator ? : in the
previous chapter which can be used to replace if...else
statements.Ithasthefollowinggeneralform
Exp1?Exp2:Exp3;
WhereExp1,Exp2,andExp3areexpressions.Noticethe
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
48/145
6/3/2016
CQuickGuide
useandplacementofthecolon.
Thevalueofa?expressionisdeterminedlikethis
Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire ?
expression.
If Exp1 is false, then Exp3 is evaluated and its
valuebecomesthevalueoftheexpression.
CLoops
You may encounter situations, when a block of code
needs to be executed several number of times. In
general, statements are executed sequentially: The first
statementinafunctionisexecutedfirst,followedbythe
second,andsoon.
Programming
languages
provide
various
control
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
49/145
6/3/2016
CQuickGuide
LoopType&Description
whileloop
forloop
50/145
6/3/2016
CQuickGuide
theloopvariable.
3
do...whileloop
Itismorelikeawhilestatement,exceptthatit
teststheconditionattheendoftheloopbody.
4
nestedloops
Youcanuseoneormoreloopsinsideanyother
while,for,ordo..whileloop.
LoopControlStatements
Loop control statements change execution from its
normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are
destroyed.
Csupportsthefollowingcontrolstatements.
S.No.
ControlStatement&Description
breakstatement
execution
to
the
statement
immediatelyfollowingthelooporswitch.
2
continuestatement
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
51/145
6/3/2016
CQuickGuide
gotostatement
Transferscontroltothelabeledstatement.
TheInfiniteLoop
A loop becomes an infinite loop if a condition never
becomes false. The for loop is traditionally used for this
purpose. Since none of the three expressions that form
the'for'looparerequired,youcanmakeanendlessloop
byleavingtheconditionalexpressionempty.
#include<stdio.h>
intmain(){
for(;;){
printf("Thisloopwillrunforever.\n");
}
return0;
}
Whentheconditionalexpressionisabsent,itisassumed
to be true. You may have an initialization and increment
expression,butCprogrammersmorecommonlyusethe
for()constructtosignifyaninfiniteloop.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
52/145
6/3/2016
CQuickGuide
CFunctions
Afunctionisagroupofstatementsthattogetherperform
atask.EveryCprogramhasatleastonefunction,which
is main(), and all the most trivial programs can define
additionalfunctions.
Youcandivideupyourcodeintoseparatefunctions.How
youdivideupyourcodeamongdifferentfunctionsisupto
you, but logically the division is such that each function
performsaspecifictask.
A function declaration tells the compiler about a
function'sname,returntype,andparameters.Afunction
definitionprovidestheactualbodyofthefunction.
The C standard library provides numerous builtin
functions that your program can call. For example,
strcat()toconcatenatetwostrings,memcpy()tocopy
onememorylocationtoanotherlocation,andmanymore
functions.
A function can also be referred as a method or a sub
routineoraprocedure,etc.
DefiningaFunction
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
53/145
6/3/2016
CQuickGuide
54/145
6/3/2016
CQuickGuide
functiondoes.
Example
Given below is the source code for a function called
max(). This function takes two parameters num1 and
num2andreturnsthemaximumvaluebetweenthetwo
/*functionreturningthemaxbetweentwonumbers*/
intmax(intnum1,intnum2){
/*localvariabledeclaration*/
intresult;
if(num1>num2)
result=num1;
else
result=num2;
returnresult;
}
FunctionDeclarations
Afunctiondeclarationtellsthecompileraboutafunction
nameandhowtocallthefunction.Theactualbodyofthe
functioncanbedefinedseparately.
Afunctiondeclarationhasthefollowingparts
return_typefunction_name(parameterlist);
55/145
6/3/2016
CQuickGuide
intmax(intnum1,intnum2);
CallingaFunction
WhilecreatingaCfunction,yougiveadefinitionofwhat
thefunctionhastodo.Touseafunction,youwillhaveto
callthatfunctiontoperformthedefinedtask.
When a program calls a function, the program control is
transferred to the called function. A called function
performsadefinedtaskandwhenitsreturnstatementis
executed or when its functionending closing brace is
reached,itreturnstheprogramcontrolbacktothemain
program.
To call a function, you simply need to pass the required
parameters along with the function name, and if the
functionreturnsavalue,thenyoucanstorethereturned
value.Forexample
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
56/145
6/3/2016
CQuickGuide
#include<stdio.h>
/*functiondeclaration*/
intmax(intnum1,intnum2);
intmain(){
/*localvariabledefinition*/
inta=100;
intb=200;
intret;
/*callingafunctiontogetmaxvalue*/
ret=max(a,b);
printf("Maxvalueis:%d\n",ret);
return0;
}
/*functionreturningthemaxbetweentwonumbers*/
intmax(intnum1,intnum2){
/*localvariabledeclaration*/
intresult;
if(num1>num2)
result=num1;
else
result=num2;
returnresult;
}
Wehavekeptmax()alongwithmain()andcompiledthe
source code. While running the final executable, it would
producethefollowingresult
Maxvalueis:200
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
57/145
6/3/2016
CQuickGuide
FunctionArguments
If a function is to use arguments, it must declare
variablesthatacceptthevaluesofthearguments.These
variables are called the formal parameters of the
function.
Formal parameters behave like other local variables
inside the function and are created upon entry into the
functionanddestroyeduponexit.
While calling a function, there are two ways in which
argumentscanbepassedtoafunction
S.No.
CallType&Description
Callbyvalue
Callbyreference
Thismethodcopiestheaddressofanargument
into the formal parameter. Inside the function,
the address is used to access the actual
argument used in the call. This means that
changes made to the parameter affect the
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
58/145
6/3/2016
CQuickGuide
argument.
CScopeRules
A scope in any programming is a region of the program
where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are
three places where variables can be declared in C
programminglanguage
Inside a function or a block which is called local
variables.
Outside of all functions which is called global
variables.
Inthedefinitionoffunctionparameterswhichare
calledformalparameters.
Let us understand what are local and global variables,
andformalparameters.
LocalVariables
Variablesthataredeclaredinsideafunctionorblockare
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
59/145
6/3/2016
CQuickGuide
intmain(){
/*localvariabledeclaration*/
inta,b;
intc;
/*actualinitialization*/
a=10;
b=20;
c=a+b;
printf("valueofa=%d,b=%dandc=%d\n",a,b,c);
return0;
}
GlobalVariables
Globalvariablesaredefinedoutsideafunction,usuallyon
top of the program. Global variables hold their values
throughoutthelifetimeofyourprogramandtheycanbe
accessed inside any of the functions defined for the
program.
Aglobalvariablecanbeaccessedbyanyfunction.Thatis,
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
60/145
6/3/2016
CQuickGuide
/*globalvariabledeclaration*/
intg;
intmain(){
/*localvariabledeclaration*/
inta,b;
/*actualinitialization*/
a=10;
b=20;
g=a+b;
printf("valueofa=%d,b=%dandg=%d\n",a,b,g);
return0;
}
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
61/145
6/3/2016
CQuickGuide
#include<stdio.h>
/*globalvariabledeclaration*/
intg=20;
intmain(){
/*localvariabledeclaration*/
intg=10;
printf("valueofg=%d\n",g);
return0;
}
FormalParameters
Formalparameters,aretreatedaslocalvariableswithin
a function and they take precedence over global
variables.Followingisanexample
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
62/145
6/3/2016
CQuickGuide
#include<stdio.h>
/*globalvariabledeclaration*/
inta=20;
intmain(){
/*localvariabledeclarationinmainfunction*/
inta=10;
intb=20;
intc=0;
printf("valueofainmain()=%d\n",a);
c=sum(a,b);
printf("valueofcinmain()=%d\n",c);
return0;
}
/*functiontoaddtwointegers*/
intsum(inta,intb){
printf("valueofainsum()=%d\n",a);
printf("valueofbinsum()=%d\n",b);
returna+b;
}
InitializingLocalandGlobalVariables
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
63/145
6/3/2016
CQuickGuide
Whenalocalvariableisdefined,itisnotinitializedbythe
system, you must initialize it yourself. Global variables
are initialized automatically by the system when you
definethemasfollows
DataType
InitialDefaultValue
int
char
'\0'
float
double
pointer
NULL
otherwise
your
program
may
produce
CArrays
Arraysakindofdatastructurethatcanstoreafixedsize
sequential collection of elements of the same type. An
arrayisusedtostoreacollectionofdata,butitisoften
more useful to think of an array as a collection of
variablesofthesametype.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
64/145
6/3/2016
CQuickGuide
DeclaringArrays
TodeclareanarrayinC,aprogrammerspecifiesthetype
oftheelementsandthenumberofelementsrequiredby
anarrayasfollows
typearrayName[arraySize];
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
65/145
6/3/2016
CQuickGuide
doublebalance[10];
Herebalanceisavariablearraywhichissufficienttohold
upto10doublenumbers.
InitializingArrays
YoucaninitializeanarrayinCeitheronebyoneorusing
asinglestatementasfollows
doublebalance[5]={1000.0,2.0,3.4,7.0,50.0};
doublebalance[]={1000.0,2.0,3.4,7.0,50.0};
You will create exactly the same array as you did in the
previous example. Following is an example to assign a
singleelementofthearray
balance[4]=50.0;
Theabovestatementassignsthe5 thelementinthearray
with a value of 50.0. All arrays have 0 as the index of
theirfirstelementwhichisalsocalledthebaseindexand
the last index of an array will be total size of the array
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
66/145
6/3/2016
CQuickGuide
AccessingArrayElements
Anelementisaccessedbyindexingthearrayname.This
isdonebyplacingtheindexoftheelementwithinsquare
bracketsafterthenameofthearray.Forexample
doublesalary=balance[9];
Theabovestatementwilltakethe10 thelementfromthe
array and assign the value to salary variable. The
following example Shows how to use all the three above
mentioned concepts viz. declaration, assignment, and
accessingarrays
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
67/145
6/3/2016
CQuickGuide
#include<stdio.h>
intmain(){
intn[10];/*nisanarrayof10integers*/
inti,j;
/*initializeelementsofarraynto0*/
for(i=0;i<10;i++){
n[i]=i+100;/*setelementatlocationitoi+100*/
}
/*outputeacharrayelement'svalue*/
for(j=0;j<10;j++){
printf("Element[%d]=%d\n",j,n[j]);
}
return0;
}
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
68/145
6/3/2016
CQuickGuide
ArraysinDetail
Arrays are important to C and should need a lot more
attention. The following important concepts related to
arrayshouldbecleartoaCprogrammer
S.No.
Concept&Description
Multidimensionalarrays
Passingarraystofunctions
Returnarrayfromafunction
Callowsafunctiontoreturnanarray.
4
Pointertoanarray
Youcangenerateapointertothefirstelement
of an array by simply specifying the array
name,withoutanyindex.
CPointers
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
69/145
6/3/2016
CQuickGuide
#include<stdio.h>
intmain(){
intvar1;
charvar2[10];
printf("Addressofvar1variable:%x\n",&var1);
printf("Addressofvar2variable:%x\n",&var2);
return0;
}
70/145
6/3/2016
CQuickGuide
WhatarePointers?
A pointer is a variable whose value is the address of
another variable, i.e., direct address of the memory
location.Likeanyvariableorconstant,youmustdeclare
a pointer before using it to store any variable address.
Thegeneralformofapointervariabledeclarationis
type*varname;
Here,typeisthepointer'sbasetypeitmustbeavalidC
data type and varname is the name of the pointer
variable. The asterisk * used to declare a pointer is the
same asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a
variable as a pointer. Take a look at some of the valid
pointerdeclarations
int*ip;/*pointertoaninteger*/
double*dp;/*pointertoadouble*/
float*fp;/*pointertoafloat*/
char*ch/*pointertoacharacter*/
Theactualdatatypeofthevalueofallpointers,whether
integer,float,character,orotherwise,isthesame,along
hexadecimalnumberthatrepresentsamemoryaddress.
The only difference between pointers of different data
typesisthedatatypeofthevariableorconstantthatthe
pointerpointsto.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
71/145
6/3/2016
CQuickGuide
HowtoUsePointers?
There are a few important operations, which we will do
withthehelpofpointersveryfrequently.(a)Wedefinea
pointervariable,(b)assigntheaddressofavariabletoa
pointer and (c) finally access the value at the address
available in the pointer variable. This is done by using
unary operator * that returns the value of the variable
located at the address specified by its operand. The
followingexamplemakesuseoftheseoperations
#include<stdio.h>
intmain(){
intvar=20;/*actualvariabledeclaration*/
int*ip;/*pointervariabledeclaration*/
ip=&var;/*storeaddressofvarinpointervariable*/
printf("Addressofvarvariable:%x\n",&var);
/*addressstoredinpointervariable*/
printf("Addressstoredinipvariable:%x\n",ip);
/*accessthevalueusingthepointer*/
printf("Valueof*ipvariable:%d\n",*ip);
return0;
}
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
72/145
6/3/2016
CQuickGuide
Addressofvarvariable:bffd8b3c
Addressstoredinipvariable:bffd8b3c
Valueof*ipvariable:20
NULLPointers
It is always a good practice to assign a NULL value to a
pointervariableincaseyoudonothaveanexactaddress
to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a
nullpointer.
The NULL pointer is a constant with a value of zero
defined in several standard libraries. Consider the
followingprogram
#include<stdio.h>
intmain(){
int*ptr=NULL;
printf("Thevalueofptris:%x\n",ptr);
return0;
}
73/145
6/3/2016
CQuickGuide
PointersinDetail
Pointershavemanybuteasyconceptsandtheyarevery
important to C programming. The following important
pointerconceptsshouldbecleartoanyCprogrammer
S.No.
Concept&Description
Pointerarithmetic
Therearefourarithmeticoperatorsthatcanbe
usedinpointers:++,,+,
2
Arrayofpointers
Pointertopointer
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
74/145
6/3/2016
CQuickGuide
PassingpointerstofunctionsinC
ReturnpointerfromfunctionsinC
CStrings
Strings are actually onedimensional array of characters
terminated by a null character '\0'. Thus a null
terminated string contains the characters that comprise
thestringfollowedbyanull.
Thefollowingdeclarationandinitializationcreateastring
consisting of the word "Hello". To hold the null character
at the end of the array, the size of the character array
containing the string is one more than the number of
charactersintheword"Hello."
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
75/145
6/3/2016
CQuickGuide
chargreeting[6]={'H','e','l','l','o','\0'};
Actually,youdonotplacethenullcharacterattheendof
astringconstant.TheCcompilerautomaticallyplacesthe
'\0' at the end of the string when it initializes the array.
Letustrytoprinttheabovementionedstring
#include<stdio.h>
intmain(){
chargreeting[6]={'H','e','l','l','o','\0'};
printf("Greetingmessage:%s\n",greeting);
return0;
}
76/145
6/3/2016
CQuickGuide
Greetingmessage:Hello
Csupportsawiderangeoffunctionsthatmanipulatenull
terminatedstrings
S.N.
1
Function&Purpose
strcpy(s1,s2)
Copiesstrings2intostrings1.
strcat(s1,s2)
Concatenatesstrings2ontotheendofstrings1.
strlen(s1)
Returnsthelengthofstrings1.
strcmp(s1,s2)
Returns0ifs1ands2arethesamelessthan0
ifs1<s2greaterthan0ifs1>s2.
strchr(s1,ch)
Returns a pointer to the first occurrence of
characterchinstrings1.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
77/145
6/3/2016
CQuickGuide
strstr(s1,s2)
Returnsapointertothefirstoccurrenceofstring
s2instrings1.
78/145
6/3/2016
CQuickGuide
strcpy(str3,str1):Hello
strcat(str1,str2):HelloWorld
strlen(str1):10
CStructures
Arrays allow to define type of variables that can hold
severaldataitemsofthesamekind.Similarlystructure
is another user defined data type available in C that
allowstocombinedataitemsofdifferentkinds.
Structures are used to represent a record. Suppose you
want to keep track of your books in a library. You might
wanttotrackthefollowingattributesabouteachbook
Title
Author
Subject
BookID
DefiningaStructure
To define a structure, you must use the struct
statement.Thestructstatementdefinesanewdatatype,
with more than one member. The format of the struct
statementisasfollows
struct[structuretag]{
memberdefinition;
memberdefinition;
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
79/145
6/3/2016
CQuickGuide
...
memberdefinition;
}[oneormorestructurevariables];
AccessingStructureMembers
To access any member of a structure, we use the
member access operator (.). The member access
operator is coded as a period between the structure
variablenameandthestructurememberthatwewishto
access. You would use the keyword struct to define
variablesofstructuretype.Thefollowingexampleshows
howtouseastructureinaprogram
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
80/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<string.h>
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};
intmain(){
structBooksBook1;/*DeclareBook1oftypeBook*/
structBooksBook2;/*DeclareBook2oftypeBook*/
/*book1specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"TelecomBillingTutorial");
Book2.book_id=6495700;
/*printBook1info*/
printf("Book1title:%s\n",Book1.title);
printf("Book1author:%s\n",Book1.author);
printf("Book1subject:%s\n",Book1.subject);
printf("Book1book_id:%d\n",Book1.book_id);
/*printBook2info*/
printf("Book2title:%s\n",Book2.title);
printf("Book2author:%s\n",Book2.author);
printf("Book2subject:%s\n",Book2.subject);
printf("Book2book_id:%d\n",Book2.book_id);
return0;
}
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
81/145
6/3/2016
CQuickGuide
StructuresasFunctionArguments
You can pass a structure as a function argument in the
samewayasyoupassanyothervariableorpointer.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
82/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<string.h>
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};
/*functiondeclaration*/
voidprintBook(structBooksbook);
intmain(){
structBooksBook1;/*DeclareBook1oftypeBook*/
structBooksBook2;/*DeclareBook2oftypeBook*/
/*book1specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"TelecomBillingTutorial");
Book2.book_id=6495700;
/*printBook1info*/
printBook(Book1);
/*PrintBook2info*/
printBook(Book2);
return0;
}
voidprintBook(structBooksbook){
printf("Booktitle:%s\n",book.title);
printf("Bookauthor:%s\n",book.author);
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
83/145
6/3/2016
CQuickGuide
printf("Bookauthor:%s\n",book.author);
printf("Booksubject:%s\n",book.subject);
printf("Bookbook_id:%d\n",book.book_id);
}
PointerstoStructures
Youcandefinepointerstostructuresinthesamewayas
youdefinepointertoanyothervariable
structBooks*struct_pointer;
Now,youcanstoretheaddressofastructurevariablein
theabovedefinedpointervariable.Tofindtheaddressof
a structure variable, place the '&' operator before the
structure'snameasfollows
struct_pointer=&Book1;
Toaccessthemembersofastructureusingapointerto
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
84/145
6/3/2016
CQuickGuide
thatstructure,youmustusetheoperatorasfollows
struct_pointer>title;
Letusrewritetheaboveexampleusingstructurepointer.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
85/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<string.h>
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};
/*functiondeclaration*/
voidprintBook(structBooks*book);
intmain(){
structBooksBook1;/*DeclareBook1oftypeBook*/
structBooksBook2;/*DeclareBook2oftypeBook*/
/*book1specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"TelecomBillingTutorial");
Book2.book_id=6495700;
/*printBook1infobypassingaddressofBook1*/
printBook(&Book1);
/*printBook2infobypassingaddressofBook2*/
printBook(&Book2);
return0;
}
voidprintBook(structBooks*book){
printf("Booktitle:%s\n",book>title);
printf("Bookauthor:%s\n",book>author);
printf("Booksubject:%s\n",book>subject);
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
86/145
6/3/2016
CQuickGuide
printf("Booksubject:%s\n",book>subject);
printf("Bookbook_id:%d\n",book>book_id);
}
BitFields
BitFieldsallowthepackingofdatainastructure.Thisis
especially useful when memory or data storage is at a
premium.Typicalexamplesinclude
Packingseveralobjectsintoamachineword.e.g.
1bitflagscanbecompacted.
Readingexternalfileformatsnonstandardfile
formatscouldbereadin,e.g.,9bitintegers.
Callowsustodothisinastructuredefinitionbyputting
:bitlengthafterthevariable.Forexample
structpacked_struct{
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
87/145
6/3/2016
CQuickGuide
unsignedintf1:1;
unsignedintf2:1;
unsignedintf3:1;
unsignedintf4:1;
unsignedinttype:4;
unsignedintmy_int:9;
}pack;
Here,thepacked_structcontains6members:Four1bit
flagsf1..f3,a4bittypeanda9bitmy_int.
C automatically packs the above bit fields as compactly
as possible, provided that the maximum length of the
fieldislessthanorequaltotheintegerwordlengthofthe
computer. If this is not the case, then some compilers
may allow memory overlap for the fields while others
wouldstorethenextfieldinthenextword.
CUnions
AunionisaspecialdatatypeavailableinCthatallows
to store different data types in the same memory
location.Youcandefineaunionwithmanymembers,but
onlyonemembercancontainavalueatanygiventime.
Unions provide an efficient way of using the same
memorylocationformultiplepurpose.
DefiningaUnion
Todefineaunion,youmustusetheunionstatementin
the same way as you did while defining a structure. The
unionstatementdefinesanewdatatypewithmorethan
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
88/145
6/3/2016
CQuickGuide
Theuniontagisoptionalandeachmemberdefinitionis
a normal variable definition, such as int i or float f or
any other valid variable definition. At the end of the
union's definition, before the final semicolon, you can
specify one or more union variables but it is optional.
Here is the way you would define a union type named
Datahavingthreemembersi,f,andstr
unionData{
inti;
floatf;
charstr[20];
}data;
89/145
6/3/2016
CQuickGuide
unionData{
inti;
floatf;
charstr[20];
};
intmain(){
unionDatadata;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}
AccessingUnionMembers
To access any member of a union, we use the member
access operator (.). The member access operator is
coded as a period between the union variable name and
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
90/145
6/3/2016
CQuickGuide
theunionmemberthatwewishtoaccess.Youwoulduse
thekeyworduniontodefinevariablesofuniontype.The
followingexampleshowshowtouseunionsinaprogram
#include<stdio.h>
#include<string.h>
unionData{
inti;
floatf;
charstr[20];
};
intmain(){
unionDatadata;
data.i=10;
data.f=220.5;
strcpy(data.str,"CProgramming");
printf("data.i:%d\n",data.i);
printf("data.f:%f\n",data.f);
printf("data.str:%s\n",data.str);
return0;
}
91/145
6/3/2016
CQuickGuide
unionData{
inti;
floatf;
charstr[20];
};
intmain(){
unionDatadata;
data.i=10;
printf("data.i:%d\n",data.i);
data.f=220.5;
printf("data.f:%f\n",data.f);
strcpy(data.str,"CProgramming");
printf("data.str:%s\n",data.str);
return0;
}
92/145
6/3/2016
CQuickGuide
data.i:10
data.f:220.500000
data.str:CProgramming
CBitFields
Suppose your C program contains a number of
TRUE/FALSE variables grouped in a structure called
status,asfollows
struct{
unsignedintwidthValidated;
unsignedintheightValidated;
}status;
93/145
6/3/2016
CQuickGuide
intmain(){
printf("Memorysizeoccupiedbystatus1:%d\n",sizeof(status1
printf("Memorysizeoccupiedbystatus2:%d\n",sizeof(status2
return0;
}
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
94/145
6/3/2016
CQuickGuide
BitFieldDeclaration
Thedeclarationofabitfieldhasthefollowingforminside
astructure
struct{
type[member_name]:width;
};
Description
type
Anintegertypethatdetermineshowa
bitfield'svalueisinterpreted.Thetype
maybeint,signedint,orunsignedint.
member_name
Thenameofthebitfield.
width
Thenumberofbitsinthebitfield.The
widthmustbelessthanorequaltothe
bitwidthofthespecifiedtype.
95/145
6/3/2016
CQuickGuide
example,ifyouneedavariabletostoreavaluefrom0to
7,thenyoucandefineabitfieldwithawidthof3bitsas
follows
struct{
unsignedintage:3;
}Age;
96/145
6/3/2016
CQuickGuide
Ctypedef
The C programming language provides a keyword called
typedef,whichyoucanusetogiveatype,anewname.
Following is an example to define a term BYTE for one
bytenumbers
typedefunsignedcharBYTE;
Afterthistypedefinition,theidentifierBYTEcanbeused
as an abbreviation for the type unsigned char, for
example..
BYTEb1,b2;
Youcanusetypedeftogiveanametoyouruserdefined
datatypesaswell.Forexample,youcanusetypedefwith
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
97/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<string.h>
typedefstructBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
}Book;
intmain(){
Bookbook;
strcpy(book.title,"CProgramming");
strcpy(book.author,"NuhaAli");
strcpy(book.subject,"CProgrammingTutorial");
book.book_id=6495407;
printf("Booktitle:%s\n",book.title);
printf("Bookauthor:%s\n",book.author);
printf("Booksubject:%s\n",book.subject);
printf("Bookbook_id:%d\n",book.book_id);
return0;
}
98/145
6/3/2016
CQuickGuide
Bookbook_id:6495407
typedefvs#define
#defineisaCdirectivewhichisalsousedtodefinethe
aliasesforvariousdatatypessimilartotypedefbutwith
thefollowingdifferences
typedef is limited to giving symbolic names to
types only where as #define can be used to
definealiasforvaluesaswell,q.,youcandefine1
asONEetc.
typedef interpretation is performed by the
compiler whereas #define statements are
processedbythepreprocessor.
The following example shows how to use #define in a
program
#include<stdio.h>
#defineTRUE1
#defineFALSE0
intmain(){
printf("ValueofTRUE:%d\n",TRUE);
printf("ValueofFALSE:%d\n",FALSE);
return0;
}
99/145
6/3/2016
CQuickGuide
ValueofTRUE:1
ValueofFALSE:0
CInput&Output
WhenwesayInput, it means to feed some data into a
program. An input can be given in the form of a file or
fromthecommandline.Cprogrammingprovidesasetof
builtinfunctionstoreadthegiveninputandfeedittothe
programasperrequirement.
WhenwesayOutput,itmeanstodisplaysomedataon
screen, printer, or in any file. C programming provides a
set of builtin functions to output the data on the
computer screen as well as to save it in text or binary
files.
TheStandardFiles
Cprogrammingtreatsallthedevicesasfiles.Sodevices
such as the display are addressed in the same way as
filesandthefollowingthreefilesareautomaticallyopened
when a program executes to provide access to the
keyboardandscreen.
StandardFile
FilePointer
Device
Standardinput
stdin
Keyboard
Standard
output
stdout
Screen
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
100/145
6/3/2016
Standarderror
CQuickGuide
stderr
Yourscreen
The file pointers are the means to access the file for
readingandwritingpurpose.Thissectionexplainshowto
readvaluesfromthescreenandhowtoprinttheresulton
thescreen.
Thegetchar()andputchar()Functions
Theintgetchar(void) function reads the next available
character from the screen and returns it as an integer.
This function reads only single character at a time. You
canusethismethodintheloopincaseyouwanttoread
morethanonecharacterfromthescreen.
The int putchar(int c) function puts the passed
character on the screen and returns the same character.
Thisfunctionputsonlysinglecharacteratatime.Youcan
use this method in the loop in case you want to display
more than one character on the screen. Check the
followingexample
#include<stdio.h>
intmain(){
intc;
printf("Enteravalue:");
c=getchar();
printf("\nYouentered:");
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
101/145
6/3/2016
CQuickGuide
putchar(c);
return0;
}
Whentheabovecodeiscompiledandexecuted,itwaits
for you to input some text. When you enter a text and
pressenter,thentheprogramproceedsandreadsonlya
singlecharacteranddisplaysitasfollows
$./a.out
Enteravalue:thisistest
Youentered:t
Thegets()andputs()Functions
The char *gets(char *s) function reads a line from
stdin into the buffer pointed to by s until either a
terminatingnewlineorEOF(EndofFile).
The int puts(const char *s) function writes the string
's'and'a'trailingnewlinetostdout.
#include<stdio.h>
intmain(){
charstr[100];
printf("Enteravalue:");
gets(str);
printf("\nYouentered:");
puts(str);
return0;
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
102/145
6/3/2016
CQuickGuide
Whentheabovecodeiscompiledandexecuted,itwaits
for you to input some text. When you enter a text and
press enter, then the program proceeds and reads the
completelinetillend,anddisplaysitasfollows
$./a.out
Enteravalue:thisistest
Youentered:Thisistest
Thescanf()andprintf()Functions
The int scanf(const char *format, ...) function reads
theinputfromthestandardinputstreamstdinandscans
thatinputaccordingtotheformatprovided.
Theint printf(const char *format, ...) function writes
the output to the standard output stream stdout and
producestheoutputaccordingtotheformatprovided.
Theformatcanbeasimpleconstantstring,butyoucan
specify %s, %d, %c, %f, etc., to print or read strings,
integer, character or float respectively. There are many
other formatting options available which can be used
basedonrequirements.Letusnowproceedwithasimple
exampletounderstandtheconceptsbetter
#include<stdio.h>
intmain(){
charstr[100];
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
103/145
6/3/2016
CQuickGuide
inti;
printf("Enteravalue:");
scanf("%s%d",str,&i);
printf("\nYouentered:%s%d",str,i);
return0;
}
Whentheabovecodeiscompiledandexecuted,itwaits
for you to input some text. When you enter a text and
press enter, then program proceeds and reads the input
anddisplaysitasfollows
$./a.out
Enteravalue:seven7
Youentered:seven7
Here,itshouldbenotedthatscanf()expectsinputinthe
same format as you provided %s and %d, which means
you have to provide valid inputs like "string integer". If
youprovide"stringstring"or"integerinteger",thenitwill
be assumed as wrong input. Secondly, while reading a
string, scanf() stops reading as soon as it encounters a
space,so"thisistest"arethreestringsforscanf().
CFileI/O
Thelastchapterexplainedthestandardinputandoutput
devices handled by C programming language. This
chapter cover how C programmers can create, open,
closetextorbinaryfilesfortheirdatastorage.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
104/145
6/3/2016
CQuickGuide
OpeningFiles
Youcanusethefopen()functiontocreateanewfileor
toopenanexistingfile.Thiscallwillinitializeanobjectof
the type FILE, which contains all the information
necessary to control the stream. The prototype of this
functioncallisasfollows
FILE*fopen(constchar*filename,constchar*mode);
Description
Opensanexistingtextfileforreadingpurpose.
Opensatextfileforwriting.Ifitdoesnotexist,
thenanewfileiscreated.Hereyourprogramwill
startwritingcontentfromthebeginningofthefile.
Opensatextfileforwritinginappendingmode.If
itdoesnotexist,thenanewfileiscreated.Here
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
105/145
6/3/2016
CQuickGuide
yourprogramwillstartappendingcontentinthe
existingfilecontent.
r+
Opensatextfileforbothreadingandwriting.
w+
Opensatextfileforbothreadingandwriting.It
firsttruncatesthefiletozerolengthifitexists,
otherwisecreatesafileifitdoesnotexist.
a+
Opensatextfileforbothreadingandwriting.It
createsthefileifitdoesnotexist.Thereadingwill
startfromthebeginningbutwritingcanonlybe
appended.
If you are going to handle binary files, then you will use
following access modes instead of the above mentioned
ones
"rb","wb","ab","rb+","r+b","wb+","w+b","ab+","a+b"
ClosingaFile
Tocloseafile,usethefclose()function.Theprototypeof
thisfunctionis
intfclose(FILE*fp);
Thefclose()functionreturnszeroonsuccess,orEOFif
thereisanerrorinclosingthefile.Thisfunctionactually
flushes any data still pending in the buffer to the file,
closesthefile,andreleasesanymemoryusedforthefile.
TheEOFisaconstantdefinedintheheaderfilestdio.h.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
106/145
6/3/2016
CQuickGuide
TherearevariousfunctionsprovidedbyCstandardlibrary
toreadandwriteafile,characterbycharacter,orinthe
formofafixedlengthstring.
WritingaFile
Following is the simplest function to write individual
characterstoastream
intfputc(intc,FILE*fp);
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
107/145
6/3/2016
CQuickGuide
#include<stdio.h>
main(){
FILE*fp;
fp=fopen("/tmp/test.txt","w+");
fprintf(fp,"Thisistestingforfprintf...\n");
fputs("Thisistestingforfputs...\n",fp);
fclose(fp);
}
ReadingaFile
Given below is the simplest function to read a single
characterfromafile
intfgetc(FILE*fp);
Thefgetc()functionreadsacharacterfromtheinputfile
referenced by fp. The return value is the character read,
or in case of any error, it returns EOF. The following
functionallowstoreadastringfromastream
char*fgets(char*buf,intn,FILE*fp);
Thefunctionsfgets()readsupton1charactersfromthe
input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to
terminatethestring.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
108/145
6/3/2016
CQuickGuide
Ifthisfunctionencountersanewlinecharacter'\n'orthe
end of the file EOF before they have read the maximum
numberofcharacters,thenitreturnsonlythecharacters
readuptothatpointincludingthenewlinecharacter.You
canalsouseintfscanf(FILE*fp,constchar*format,
...) function to read strings from a file, but it stops
readingafterencounteringthefirstspacecharacter.
#include<stdio.h>
main(){
FILE*fp;
charbuff[255];
fp=fopen("/tmp/test.txt","r");
fscanf(fp,"%s",buff);
printf("1:%s\n",buff);
fgets(buff,255,(FILE*)fp);
printf("2:%s\n",buff);
fgets(buff,255,(FILE*)fp);
printf("3:%s\n",buff);
fclose(fp);
}
Whentheabovecodeiscompiledandexecuted,itreads
the file created in the previous section and produces the
followingresult
1:This
2:istestingforfprintf...
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
109/145
6/3/2016
CQuickGuide
3:Thisistestingforfputs...
Let'sseealittlemoreindetailaboutwhathappenedhere.
First, fscanf() read just This because after that, it
encountered a space, second call is for fgets() which
reads the remaining line till it encountered end of line.
Finally, the last call fgets() reads the second line
completely.
BinaryI/OFunctions
Therearetwofunctions,thatcanbeusedforbinaryinput
andoutput
size_tfread(void*ptr,size_tsize_of_elements,size_tnumber_of_e
size_tfwrite(constvoid*ptr,size_tsize_of_elements,size_t
CPreprocessors
TheCPreprocessorisnotapartofthecompiler,butisa
separate step in the compilation process. In simple
terms, a C Preprocessor is just a text substitution tool
anditinstructsthecompilertodorequiredpreprocessing
before the actual compilation. We'll refer to the C
PreprocessorasCPP.
All preprocessor commands begin with a hash symbol
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
110/145
6/3/2016
CQuickGuide
Description
#define
Substitutesapreprocessormacro.
#include
Insertsaparticularheaderfromanotherfile.
#undef
Undefinesapreprocessormacro.
#ifdef
Returnstrueifthismacroisdefined.
#ifndef
Returnstrueifthismacroisnotdefined.
#if
Testsifacompiletimeconditionistrue.
#else
Thealternativefor#if.
#elif
#elseand#ifinonestatement.
#endif
Endspreprocessorconditional.
#error
Printserrormessageonstderr.
#pragma
Issuesspecialcommandstothecompiler,
usingastandardizedmethod.
PreprocessorsExamples
Analyze the following examples to understand various
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
111/145
6/3/2016
CQuickGuide
directives.
#defineMAX_ARRAY_LENGTH20
ThesedirectivestelltheCPPtogetstdio.hfromSystem
Librariesandaddthetexttothecurrentsourcefile.The
next line tells CPP to get myheader.h from the local
directoryandaddthecontenttothecurrentsourcefile.
#undefFILE_SIZE
#defineFILE_SIZE42
IttellstheCPPtoundefineexistingFILE_SIZEanddefine
itas42.
#ifndefMESSAGE
#defineMESSAGE"Youwish!"
#endif
IttellstheCPPtodefineMESSAGEonlyifMESSAGEisn't
alreadydefined.
#ifdefDEBUG
/*Yourdebuggingstatementshere*/
#endif
112/145
6/3/2016
CQuickGuide
DEBUGisdefined.ThisisusefulifyoupasstheDDEBUG
flag to the gcc compiler at the time of compilation. This
willdefineDEBUG,soyoucanturndebuggingonandoff
ontheflyduringcompilation.
PredefinedMacros
ANSICdefinesanumberofmacros.Althougheachoneis
availableforuseinprogramming,thepredefinedmacros
shouldnotbedirectlymodified.
Macro
Description
__DATE__
Thecurrentdateasacharacterliteralin
"MMMDDYYYY"format.
__TIME__
Thecurrenttimeasacharacterliteralin
"HH:MM:SS"format.
__FILE__
Thiscontainsthecurrentfilenameasastring
literal.
__LINE__
Thiscontainsthecurrentlinenumberasa
decimalconstant.
__STDC__
Definedas1whenthecompilercomplieswith
theANSIstandard.
Let'strythefollowingexample
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
113/145
6/3/2016
CQuickGuide
#include<stdio.h>
main(){
printf("File:%s\n",__FILE__);
printf("Date:%s\n",__DATE__);
printf("Time:%s\n",__TIME__);
printf("Line:%d\n",__LINE__);
printf("ANSI:%d\n",__STDC__);
}
PreprocessorOperators
TheCpreprocessoroffersthefollowingoperatorstohelp
createmacros
TheMacroContinuation(\)Operator
Amacroisnormallyconfinedtoasingleline.Themacro
continuationoperator(\)isusedtocontinueamacrothat
istoolongforasingleline.Forexample
#definemessage_for(a,b)\
printf(#a"and"#b":Weloveyou!\n")
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
114/145
6/3/2016
CQuickGuide
TheStringize(#)Operator
Thestringizeornumbersignoperator('#'),whenused
within a macro definition, converts a macro parameter
intoastringconstant.Thisoperatormaybeusedonlyin
a macro having a specified argument or parameter list.
Forexample
#include<stdio.h>
#definemessage_for(a,b)\
printf(#a"and"#b":Weloveyou!\n")
intmain(void){
message_for(Carole,Debra);
return0;
}
TheTokenPasting(##)Operator
Thetokenpastingoperator(##)withinamacrodefinition
combinestwoarguments.Itpermitstwoseparatetokens
in the macro definition to be joined into a single token.
Forexample
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
115/145
6/3/2016
CQuickGuide
#include<stdio.h>
#definetokenpaster(n)printf("token"#n"=%d",token##n)
intmain(void){
inttoken34=40;
tokenpaster(34);
return0;
}
TheDefined()Operator
The preprocessor defined operator is used in constant
expressions to determine if an identifier is defined using
#define.Ifthespecifiedidentifierisdefined,thevalueis
true(nonzero).Ifthesymbolisnotdefined,thevalueis
false(zero).Thedefinedoperatorisspecifiedasfollows
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
116/145
6/3/2016
CQuickGuide
#include<stdio.h>
#if!defined(MESSAGE)
#defineMESSAGE"Youwish!"
#endif
intmain(void){
printf("Hereisthemessage:%s\n",MESSAGE);
return0;
}
ParameterizedMacros
OneofthepowerfulfunctionsoftheCPPistheabilityto
simulate functions using parameterized macros. For
example,wemighthavesomecodetosquareanumber
asfollows
intsquare(intx){
returnx*x;
}
Wecanrewriteabovethecodeusingamacroasfollows
#definesquare(x)((x)*(x))
117/145
6/3/2016
CQuickGuide
CHeaderFiles
Aheaderfileisafilewithextension.h which contains C
function declarations and macro definitions to be shared
between several source files. There are two types of
headerfiles:thefilesthattheprogrammerwritesandthe
filesthatcomeswithyourcompiler.
You request to use a header file in your program by
including it with the C preprocessing directive #include,
likeyouhaveseeninclusionofstdio.hheaderfile,which
comesalongwithyourcompiler.
Includingaheaderfileisequaltocopyingthecontentof
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
118/145
6/3/2016
CQuickGuide
theheaderfilebutwedonotdoitbecauseitwillbeerror
prone and it is not a good idea to copy the content of a
header file in the source files, especially if we have
multiplesourcefilesinaprogram.
AsimplepracticeinCorC++programsisthatwekeep
all the constants, macros, system wide global variables,
and function prototypes in the header files and include
thatheaderfilewhereveritisrequired.
IncludeSyntax
Both the user and the system header files are included
using the preprocessing directive #include. It has the
followingtwoforms
#include<file>
Thisformisusedforsystemheaderfiles.Itsearchesfor
afilenamed'file'inastandardlistofsystemdirectories.
YoucanprependdirectoriestothislistwiththeIoption
whilecompilingyoursourcecode.
#include"file"
Thisformisusedforheaderfilesofyourownprogram.It
searchesforafilenamed'file'inthedirectorycontaining
the current file. You can prepend directories to this list
withtheIoptionwhilecompilingyoursourcecode.
IncludeOperation
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
119/145
6/3/2016
CQuickGuide
thecompilerwillseethesametokenstreamasitwouldif
program.cread.
intx;
char*test(void);
intmain(void){
puts(test());
}
OnceOnlyHeaders
Ifaheaderfilehappenstobeincludedtwice,thecompiler
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
120/145
6/3/2016
CQuickGuide
willprocessitscontentstwiceanditwillresultinanerror.
Thestandardwaytopreventthisistoenclosetheentire
realcontentsofthefileinaconditional,likethis
#ifndefHEADER_FILE
#defineHEADER_FILE
theentireheaderfilefile
#endif
Thisconstructiscommonlyknownasawrapper#ifndef.
Whentheheaderisincludedagain,theconditionalwillbe
false,becauseHEADER_FILEisdefined.Thepreprocessor
will skip over the entire contents of the file, and the
compilerwillnotseeittwice.
ComputedIncludes
Sometimes it is necessary to select one of the several
different header files to be included into your program.
Forinstance,theymightspecifyconfigurationparameters
to be used on different sorts of operating systems. You
coulddothiswithaseriesofconditionalsasfollows
#ifSYSTEM_1
#include"system_1.h"
#elifSYSTEM_2
#include"system_2.h"
#elifSYSTEM_3
...
#endif
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
121/145
6/3/2016
CQuickGuide
CTypeCasting
Typecastingisawaytoconvertavariablefromonedata
type to another data type. For example, if you want to
store a 'long' value into a simple integer then you can
type cast 'long' to 'int'. You can convert the values from
onetypetoanotherexplicitlyusingthecastoperatoras
follows
(type_name)expression
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
122/145
6/3/2016
CQuickGuide
#include<stdio.h>
main(){
intsum=17,count=5;
doublemean;
mean=(double)sum/count;
printf("Valueofmean:%f\n",mean);
}
IntegerPromotion
Integer promotion is the process by which values of
integer type "smaller" than int or unsigned int are
converted either to int or unsigned int. Consider an
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
123/145
6/3/2016
CQuickGuide
exampleofaddingacharacterwithaninteger
#include<stdio.h>
main(){
inti=17;
charc='c';/*asciivalueis99*/
intsum;
sum=i+c;
printf("Valueofsum:%d\n",sum);
}
UsualArithmeticConversion
The usual arithmetic conversions are implicitly
performed to cast their values to a common type. The
compilerfirstperformsintegerpromotioniftheoperands
still have different types, then they are converted to the
typethatappearshighestinthefollowinghierarchy
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
124/145
6/3/2016
CQuickGuide
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
125/145
6/3/2016
CQuickGuide
#include<stdio.h>
main(){
inti=17;
charc='c';/*asciivalueis99*/
floatsum;
sum=i+c;
printf("Valueofsum:%f\n",sum);
}
Here,itissimpletounderstandthatfirstcgetsconverted
to integer, but as the final value is double, usual
arithmeticconversionappliesandthecompilerconvertsi
andcinto'float'andaddsthemyieldinga'float'result.
CErrorHandling
As such, C programming does not provide direct support
for error handling but being a system programming
language,itprovidesyouaccessatlowerlevelintheform
ofreturnvalues.MostoftheCorevenUnixfunctioncalls
return 1 or NULL in case of any error and set an error
codeerrno.Itissetasaglobalvariableandindicatesan
error occurred during any function call. You can find
variouserrorcodesdefinedin<error.h>headerfile.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
126/145
6/3/2016
CQuickGuide
errno,perror().andstrerror()
The C programming language provides perror() and
strerror()functionswhichcanbeusedtodisplaythetext
messageassociatedwitherrno.
Theperror()functiondisplaysthestringyoupass
to it, followed by a colon, a space, and then the
textualrepresentationofthecurrenterrnovalue.
The strerror() function, which returns a pointer
tothetextualrepresentationofthecurrenterrno
value.
Let'strytosimulateanerrorconditionandtrytoopena
file which does not exist. Here I'm using both the
functionstoshowtheusage,butyoucanuseoneormore
ways of printing your errors. Second important point to
note is that you should use stderr file stream to output
alltheerrors.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
127/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<errno.h>
#include<string.h>
externinterrno;
intmain(){
FILE*pf;
interrnum;
pf=fopen("unexist.txt","rb");
if(pf==NULL){
errnum=errno;
fprintf(stderr,"Valueoferrno:%d\n",errno);
perror("Errorprintedbyperror");
fprintf(stderr,"Erroropeningfile:%s\n",strerror(errnum
}
else{
fclose(pf);
}
return0;
}
DividebyZeroErrors
Itisacommonproblemthatatthetimeofdividingany
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
128/145
6/3/2016
CQuickGuide
number,programmersdonotcheckifadivisoriszeroand
finallyitcreatesaruntimeerror.
Thecodebelowfixesthisbycheckingifthedivisoriszero
beforedividing
#include<stdio.h>
#include<stdlib.h>
main(){
intdividend=20;
intdivisor=0;
intquotient;
if(divisor==0){
fprintf(stderr,"Divisionbyzero!Exiting...\n");
exit(1);
}
quotient=dividend/divisor;
fprintf(stderr,"Valueofquotient:%d\n",quotient);
exit(0);
}
ProgramExitStatus
It is a common practice to exit with a value of
EXIT_SUCCESS in case of program coming out after a
successful operation. Here, EXIT_SUCCESS is a macro
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
129/145
6/3/2016
CQuickGuide
anditisdefinedas0.
If you have an error condition in your program and you
are coming out then you should exit with a status
EXIT_FAILUREwhichisdefinedas1.Solet'swriteabove
programasfollows
#include<stdio.h>
#include<stdlib.h>
main(){
intdividend=20;
intdivisor=5;
intquotient;
if(divisor==0){
fprintf(stderr,"Divisionbyzero!Exiting...\n");
exit(EXIT_FAILURE);
}
quotient=dividend/divisor;
fprintf(stderr,"Valueofquotient:%d\n",quotient);
exit(EXIT_SUCCESS);
}
CRecursion
Recursion is the process of repeating items in a self
similar way. In programming languages, if a program
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
130/145
6/3/2016
CQuickGuide
NumberFactorial
The following example calculates the factorial of a given
numberusingarecursivefunction
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
131/145
6/3/2016
CQuickGuide
#include<stdio.h>
intfactorial(unsignedinti){
if(i<=1){
return1;
}
returni*factorial(i1);
}
intmain(){
inti=15;
printf("Factorialof%dis%d\n",i,factorial(i));
return0;
}
FibonacciSeries
ThefollowingexamplegeneratestheFibonacciseriesfor
agivennumberusingarecursivefunction
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
132/145
6/3/2016
CQuickGuide
#include<stdio.h>
intfibonaci(inti){
if(i==0){
return0;
}
if(i==1){
return1;
}
returnfibonaci(i1)+fibonaci(i2);
}
intmain(){
inti;
for(i=0;i<10;i++){
printf("%d\t%n",fibonaci(i));
}
return0;
}
13
21
CVariableArguments
Sometimes,youmaycomeacrossasituation,whenyou
wanttohaveafunction,whichcantakevariablenumber
of arguments, i.e., parameters, instead of predefined
number of parameters. The C programming language
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
133/145
6/3/2016
CQuickGuide
providesasolutionforthissituationandyouareallowed
todefineafunctionwhichcanacceptvariablenumberof
parameters based on your requirement. The following
exampleshowsthedefinitionofsuchafunction.
intfunc(int,...){
.
.
.
}
intmain(){
func(1,2,3);
func(1,2,3,4);
}
134/145
6/3/2016
CQuickGuide
file.
Use int parameter and va_start macro to
initializetheva_listvariabletoanargumentlist.
Themacrova_startisdefinedinstdarg.hheader
file.
Use va_arg macro and va_list variable to
accesseachiteminargumentlist.
Use a macro va_end to clean up the memory
assignedtova_listvariable.
Now let us follow the above steps and write down a
simple function which can take the variable number of
parametersandreturntheiraverage
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
135/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<stdarg.h>
doubleaverage(intnum,...){
va_listvalist;
doublesum=0.0;
inti;
/*initializevalistfornumnumberofarguments*/
va_start(valist,num);
/*accessalltheargumentsassignedtovalist*/
for(i=0;i<num;i++){
sum+=va_arg(valist,int);
}
/*cleanmemoryreservedforvalist*/
va_end(valist);
returnsum/num;
}
intmain(){
printf("Averageof2,3,4,5=%f\n",average(4,2,3,4,5));
printf("Averageof5,10,15=%f\n",average(3,5,10,15));
}
136/145
6/3/2016
CQuickGuide
Averageof5,10,15=10.000000
CMemoryManagement
This chapter explains dynamic memory management in
C. The C programming language provides several
functionsformemoryallocationandmanagement.These
functionscanbefoundinthe<stdlib.h>headerfile.
S.N.
1
Function&Description
void*calloc(intnum,intsize)
This function allocates an array of num
elements each of which size in bytes will be
size.
voidfree(void*address)
This function releases a block of memory block
specifiedbyaddress.
void*malloc(intnum)
This function allocates an array of num bytes
andleavetheminitialized.
void*realloc(void*address,intnewsize)
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
137/145
6/3/2016
CQuickGuide
AllocatingMemoryDynamically
While programming, if you are aware of the size of an
array,thenitiseasyandyoucandefineitasanarray.For
example,tostoreanameofanyperson,itcangouptoa
maximum of 100 characters, so you can define
somethingasfollows
charname[100];
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
138/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain(){
charname[100];
char*description;
strcpy(name,"ZaraAli");
/*allocatememorydynamically*/
description=malloc(200*sizeof(char));
if(description==NULL){
fprintf(stderr,"Errorunabletoallocaterequiredmemory\n
}
else{
strcpy(description,"ZaraaliaDPSstudentinclass10th"
}
printf("Name=%s\n",name);
printf("Description:%s\n",description);
}
Soyouhavecompletecontrolandyoucanpassanysize
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
139/145
6/3/2016
CQuickGuide
ResizingandReleasingMemory
When your program comes out, operating system
automatically release all the memory allocated by your
programbutasagoodpracticewhenyouarenotinneed
of memory anymore then you should release that
memorybycallingthefunctionfree().
Alternatively,youcanincreaseordecreasethesizeofan
allocatedmemoryblockbycallingthefunctionrealloc().
Let us check the above program once again and make
useofrealloc()andfree()functions
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
140/145
6/3/2016
CQuickGuide
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain(){
charname[100];
char*description;
strcpy(name,"ZaraAli");
/*allocatememorydynamically*/
description=malloc(30*sizeof(char));
if(description==NULL){
fprintf(stderr,"Errorunabletoallocaterequiredmemory\n
}
else{
strcpy(description,"ZaraaliaDPSstudent.");
}
/*supposeyouwanttostorebiggerdescription*/
description=realloc(description,100*sizeof(char));
if(description==NULL){
fprintf(stderr,"Errorunabletoallocaterequiredmemory\n
}
else{
strcat(description,"Sheisinclass10th");
}
printf("Name=%s\n",name);
printf("Description:%s\n",description);
/*releasememoryusingfree()function*/
free(description);
}
141/145
6/3/2016
CQuickGuide
producesthefollowingresult.
Name=ZaraAli
Description:ZaraaliaDPSstudent.Sheisinclass10th
Youcantrytheaboveexamplewithoutreallocatingextra
memory, and strcat() function will give an error due to
lackofavailablememoryindescription.
CCommandLineArguments
Itispossibletopasssomevaluesfromthecommandline
to your C programs when they are executed. These
valuesarecalledcommandlinearguments and many
times they are important for your program especially
when you want to control your program from outside
insteadofhardcodingthosevaluesinsidethecode.
The command line arguments are handled using main()
function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
Followingisasimpleexamplewhichchecksifthereisany
argument supplied from the command line and take
actionaccordingly
#include<stdio.h>
intmain(intargc,char*argv[]){
if(argc==2){
printf("Theargumentsuppliedis%s\n",argv[1]);
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
142/145
6/3/2016
CQuickGuide
}
elseif(argc>2){
printf("Toomanyargumentssupplied.\n");
}
else{
printf("Oneargumentexpected.\n");
}
}
143/145
6/3/2016
CQuickGuide
if(argc==2){
printf("Theargumentsuppliedis%s\n",argv[1]);
}
elseif(argc>2){
printf("Toomanyargumentssupplied.\n");
}
else{
printf("Oneargumentexpected.\n");
}
}
PreviousPage
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
NextPage
144/145
6/3/2016
CQuickGuide
Advertisements
Write for us
FAQ's
Helping
Contact
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm
go
145/145