Vous êtes sur la page 1sur 145

6/3/2016

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;
}

For most of the examples given in this


tutorial, you will find a Try it option in our
websitecodesectionsatthetoprightcorner
that will take you to the online compiler. So
justmakeuseofitandenjoyyourlearning.

LocalEnvironmentSetup
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

4/145

6/3/2016

CQuickGuide

If you want to set up your environment for C


programming language, you need the following two
softwaretoolsavailableonyourcomputer,(a)TextEditor
and(b)TheCCompiler.

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)

If GCC is not installed, then you will have to install it


yourself using the detailed instructions available at
http://gcc.gnu.org/install/
This tutorial has been written based on Linux and all the
given examples have been compiled on the Cent OS
flavoroftheLinuxsystem.

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,

, and follow the link to the MinGW

download page. Download the latest version of the


MinGW installation program, which should be named
MinGW<version>.exe.
While installing Min GW, at a minimum, you must install
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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

Let us look at a simple code that would print the words


"HelloWorld"
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

8/145

6/3/2016

CQuickGuide

#include<stdio.h>
intmain(){
/*myfirstprograminC*/
printf("Hello,World!\n");

return0;
}

Let us take a look at the various parts of the above


program
Thefirstlineoftheprogram#include<stdio.h>is
apreprocessorcommand,whichtellsaCcompiler
to include stdio.h file before going to actual
compilation.
The next line int main() is the main function
wheretheprogramexecutionbegins.
The next line /*...*/ will be ignored by the
compiler and it has been put to add additional
comments in the program. So such lines are
calledcommentsintheprogram.
The next line printf(...) is another function
available in C which causes the message "Hello,
World!"tobedisplayedonthescreen.
The next line return 0 terminates the main()
functionandreturnsthevalue0.

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

reserved words may not be used as constants or


variablesoranyotheridentifiernames.
auto

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.

The array types and structure types are referred


collectivelyastheaggregatetypes.Thetypeofafunction
specifies the type of the function's return value. We will
see the basic types in the following section, whereas
othertypeswillbecoveredintheupcomingchapters.

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

To get the exact size of a type or a variable on a


particularplatform,youcanusethesizeofoperator.The
expressions sizeof(type) yields the storage size of the
objectortypeinbytes.Givenbelowisanexampletoget
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

16/145

6/3/2016

CQuickGuide

thesizeofinttypeonanymachine
#include<stdio.h>
#include<limits.h>
intmain(){
printf("Storagesizeforint:%d\n",sizeof(int));

return0;
}

When you compile and execute the above program, it


producesthefollowingresultonLinux
Storagesizeforint:4

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

The header file float.h defines macros that allow you to


use these values and other details about the binary
representation of real numbers in your programs. The
following example prints the storage space taken by a
floattypeanditsrangevalues
#include<stdio.h>
#include<float.h>
intmain(){
printf("Storagesizeforfloat:%d\n",sizeof(float));
printf("Minimumfloatpositivevalue:%E\n",FLT_MIN);
printf("Maximumfloatpositivevalue:%E\n",FLT_MAX);
printf("Precisionvalue:%d\n",FLT_DIG);

return0;
}

When you compile and execute the above program, it


producesthefollowingresultonLinux
Storagesizeforfloat:4
Minimumfloatpositivevalue:1.175494E38
Maximumfloatpositivevalue:3.402823E+38
Precisionvalue:6

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

a specific type, which determines the size and layout of


the variable's memory the range of values that can be
storedwithinthatmemoryandthesetofoperationsthat
canbeappliedtothevariable.
Thenameofavariablecanbecomposedofletters,digits,
andtheunderscorecharacter.Itmustbeginwitheithera
letter or an underscore. Upper and lowercase letters are
distinct because C is casesensitive. Based on the basic
typesexplainedinthepreviouschapter,therewillbethe
followingbasicvariabletypes
Type

Description

char

Typicallyasingleoctet(onebyte).Thisisan
integertype.

int

Themostnaturalsizeofintegerforthe
machine.

float

Asingleprecisionfloatingpointvalue.

double

Adoubleprecisionfloatingpointvalue.

void

Representstheabsenceoftype.

C programming language also allows to define various


other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array,
Structure, Union, etc. For this chapter, let us study only
basicvariabletypes.
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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;

Here, type must be a valid C data type including char,


w_char, int, float, double, bool, or any userdefined
object and variable_list may consist of one or more
identifier names separated by commas. Some valid
declarationsareshownhere
inti,j,k;
charc,ch;
floatf,salary;
doubled;

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'.

For definition without an initializer: variables with static


storage duration are implicitly initialized with NULL (all
bytes have the value 0) the initial value of all other
variablesareundefined.

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

Try the following example, where variables have been


declared at the top, but they have been defined and
initializedinsidethemainfunction
#include<stdio.h>
//Variabledeclaration:
externinta,b;
externintc;
externfloatf;
intmain(){
/*variabledefinition:*/
inta,b;
intc;
floatf;

/*actualinitialization*/
a=10;
b=20;

c=a+b;
printf("valueofc:%d\n",c);
f=70.0/3.0;
printf("valueoff:%f\n",f);

return0;
}

When the above code is compiled and executed, it


producesthefollowingresult
valueofc:30
valueoff:23.333334

The same concept applies on function declaration where


http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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

An integer literal can also have a suffix that is a


combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase
andcanbeinanyorder.
Herearesomeexamplesofintegerliterals
212/*Legal*/
215u/*Legal*/
0xFeeL/*Legal*/
078/*Illegal:8isnotanoctaldigit*/
032UU/*Illegal:cannotrepeatasuffix*/

Following are other examples of various types of integer


literals
85/*decimal*/
0213/*octal*/
0x4b/*hexadecimal*/
30/*int*/
30u/*unsignedint*/
30l/*long*/
30ul/*unsignedlong*/

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

While representing decimal form, you must include the


decimal point, the exponent, or both and while
representing exponential form, you must include the
integer part, the fractional part, or both. The signed
exponentisintroducedbyeorE.
Herearesomeexamplesoffloatingpointliterals
3.14159/*Legal*/
314159E5L/*Legal*/
510E/*Illegal:incompleteexponent*/
210f/*Illegal:nodecimalorexponent*/
.e55/*Illegal:missingintegerorfraction*/

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
HelloWorld

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
valueofarea:50

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
valueofarea:50

Note that it is a good programming practice to define


constantsinCAPITALS.

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;
}

The example above defines two variables with in the


same storage class. 'auto' can only be used within
functions,i.e.,localvariables.

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

will be stored in a register. It means that it MIGHT be


stored in a register depending on hardware and
implementationrestrictions.

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
iis6andcountis4
iis7andcountis3
iis8andcountis2
iis9andcountis1
iis10andcountis0

TheexternStorageClass
Theexternstorageclassisusedtogiveareferenceofa
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

34/145

6/3/2016

CQuickGuide

global variable that is visible to ALL the program files.


When you use 'extern', the variable cannot be initialized
however,itpointsthevariablenameatastoragelocation
thathasbeenpreviouslydefined.
When you have multiple files and you define a global
variableorfunction,whichwillalsobeusedinotherfiles,
then extern will be used in another file to provide the
reference of defined variable or function. Just for
understanding,externisusedtodeclareaglobalvariable
orfunctioninanotherfile.
The extern modifier is most commonly used when there
aretwoormorefilessharingthesameglobalvariablesor
functionsasexplainedbelow.
FirstFile:main.c
#include<stdio.h>

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

Itwillproducetheexecutableprograma.out. When this


programisexecuted,itproducesthefollowingresult
5

COperators
Anoperatorisasymbolthattellsthecompilertoperform
specific mathematical or logical functions. C language is
richinbuiltinoperatorsandprovidesthefollowingtypes
ofoperators
ArithmeticOperators
RelationalOperators
LogicalOperators
BitwiseOperators
AssignmentOperators
MiscOperators

We will, in this chapter, look into the way each operator


http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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

C programming language assumes any nonzero and


nonnullvaluesastrue,andifitiseitherzeroornull,
thenitisassumedasfalsevalue.
C programming language provides the following types of
decisionmakingstatements.
S.No.

Statement&Description

ifstatement

An if statement consists of a boolean


expression

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

Youcanuseoneiforelseif statement inside


anotheriforelseifstatement(s).
4

switchstatement

A switch statement allows a variable to be


testedforequalityagainstalistofvalues.
5

nestedswitchstatements

You can use one switch statement inside


anotherswitchstatement(s).

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

structures that allow for more complicated execution


paths.
A loop statement allows us to execute a statement or
group of statements multiple times. Given below is the
general form of a loop statement in most of the
programminglanguages

http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

49/145

6/3/2016

CQuickGuide

C programming language provides the following types of


loopstohandleloopingrequirements.
S.No.

LoopType&Description

whileloop

Repeats a statement or group of statements


while a given condition is true. It tests the
conditionbeforeexecutingtheloopbody.
2

forloop

Executes a sequence of statements multiple


times and abbreviates the code that manages
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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

Terminatesthelooporswitch statement and


transfers

execution

to

the

statement

immediatelyfollowingthelooporswitch.
2

continuestatement

http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

51/145

6/3/2016

CQuickGuide

Causes the loop to skip the remainder of its


bodyandimmediatelyretestitsconditionprior
toreiterating.
3

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

NOTE You can terminate an infinite loop by pressing


Ctrl+Ckeys.

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

The general form of a function definition in C


programminglanguageisasfollows
return_typefunction_name(parameterlist){
bodyofthefunction
}

A function definition in C programming consists of a


functionheaderandafunctionbody.Herearealltheparts
ofafunction
Return Type A function may return a value.
The return_type is the data type of the value
the function returns. Some functions perform the
desired operations without returning a value. In
thiscase,thereturn_typeisthekeywordvoid.
FunctionNameThisistheactualnameofthe
function. The function name and the parameter
listtogetherconstitutethefunctionsignature.
ParametersAparameterislikeaplaceholder.
When a function is invoked, you pass a value to
theparameter.Thisvalueisreferredtoasactual
parameterorargument.Theparameterlistrefers
tothetype,order,andnumberoftheparameters
of a function. Parameters are optional that is, a
functionmaycontainnoparameters.
Function Body The function body contains a
collection of statements that define what the
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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);

For the above defined function max(), the function


declarationisasfollows
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

55/145

6/3/2016

CQuickGuide

intmax(intnum1,intnum2);

Parameter names are not important in function


declarationonlytheirtypeisrequired,sothefollowingis
alsoavaliddeclaration
intmax(int,int);

Function declaration is required when you define a


function in one source file and you call that function in
anotherfile.Insuchcase,youshoulddeclarethefunction
atthetopofthefilecallingthefunction.

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

This method copies the actual value of an


argument into the formal parameter of the
function. In this case, changes made to the
parameterinsidethefunctionhavenoeffecton
theargument.
2

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.

By default, C uses call by value to pass arguments. In


general,itmeansthecodewithinafunctioncannotalter
theargumentsusedtocallthefunction.

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

called local variables. They can be used only by


statementsthatareinsidethatfunctionorblockofcode.
Local variables are not known to functions outside their
own.Thefollowingexampleshowshowlocalvariablesare
used.Hereallthevariablesa,b,andcarelocaltomain()
function.
#include<stdio.h>

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

a global variable is available for use throughout your


entire program after its declaration. The following
program show how global variables are used in a
program.
#include<stdio.h>

/*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;
}

A program can have same name for local and global


variables but the value of local variable inside a function
willtakepreference.Hereisanexample

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
valueofg=10

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
valueofainmain()=10
valueofainsum()=10
valueofbinsum()=20
valueofcinmain()=30

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

It is a good programming practice to initialize variables


properly,

otherwise

your

program

may

produce

unexpected results, because uninitialized variables will


take some garbage value already available at their
memorylocation.

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

Instead of declaring individual variables, such as


number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0],
numbers[1],and...,numbers[99]torepresentindividual
variables.Aspecificelementinanarrayisaccessedbyan
index.
All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highestaddresstothelastelement.

DeclaringArrays
TodeclareanarrayinC,aprogrammerspecifiesthetype
oftheelementsandthenumberofelementsrequiredby
anarrayasfollows
typearrayName[arraySize];

This is called a singledimensional array. The arraySize


must be an integer constant greater than zero andtype
can be any valid C data type. For example, to declare a
10elementarraycalledbalanceoftypedouble,usethis
statement

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};

The number of values between braces { } cannot be


larger than the number of elements that we declare for
thearraybetweensquarebrackets[].
Ifyouomitthesizeofthearray,anarrayjustbigenough
toholdtheinitializationiscreated.Therefore,ifyouwrite

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

minus 1. Shown below is the pictorial representation of


thearraywediscussedabove

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
Element[0]=100
Element[1]=101
Element[2]=102
Element[3]=103
Element[4]=104
Element[5]=105
Element[6]=106
Element[7]=107
Element[8]=108
Element[9]=109

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

C supports multidimensional arrays. The


simplest form of the multidimensional array is
thetwodimensionalarray.
2

Passingarraystofunctions

You can pass to the function a pointer to an


arraybyspecifyingthearray'snamewithoutan
index.
3

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

Pointers in C are easy and fun to learn. Some C


programming tasks are performed more easily with
pointers, and other tasks, such as dynamic memory
allocation,cannotbeperformedwithoutusingpointers.So
it becomes necessary to learn pointers to become a
perfectCprogrammer.Let'sstartlearningtheminsimple
andeasysteps.
As you know, every variable is a memory location and
everymemorylocationhasitsaddressdefinedwhichcan
be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following
example,whichprintstheaddressofthevariablesdefined

#include<stdio.h>
intmain(){
intvar1;
charvar2[10];
printf("Addressofvar1variable:%x\n",&var1);
printf("Addressofvar2variable:%x\n",&var2);
return0;
}

When the above code is compiled and executed, it


producesthefollowingresult
Addressofvar1variable:bff5a400
Addressofvar2variable:bff5a3f6
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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;
}

When the above code is compiled and executed, it


producesthefollowingresult

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
Thevalueofptris0

In most of the operating systems, programs are not


permitted to access memory at address 0 because that
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

73/145

6/3/2016

CQuickGuide

memory is reserved by the operating system. However,


thememoryaddress0hasspecialsignificanceitsignals
thatthepointerisnotintendedtopointtoanaccessible
memorylocation.Butbyconvention,ifapointercontains
thenull(zero)value,itisassumedtopointtonothing.
Tocheckforanullpointer,youcanusean'if'statement
asfollows
if(ptr)/*succeedsifpisnotnull*/
if(!ptr)/*succeedsifpisnull*/

PointersinDetail
Pointershavemanybuteasyconceptsandtheyarevery
important to C programming. The following important
pointerconceptsshouldbecleartoanyCprogrammer
S.No.

Concept&Description

Pointerarithmetic

Therearefourarithmeticoperatorsthatcanbe
usedinpointers:++,,+,
2

Arrayofpointers

You can define arrays to hold a number of


pointers.
3

Pointertopointer

http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

74/145

6/3/2016

CQuickGuide

C allows you to have pointer on a pointer and


soon.
4

PassingpointerstofunctionsinC

Passing an argument by reference or by


address enable the passed argument to be
changed in the calling function by the called
function.
5

ReturnpointerfromfunctionsinC

C allows a function to return a pointer to the


local variable, static variable, and dynamically
allocatedmemoryaswell.

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'};

If you follow the rule of array initialization then you can


writetheabovestatementasfollows
chargreeting[]="Hello";

Following is the memory presentation of the above


definedstringinC/C++

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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.

The following example uses some of the above


mentionedfunctions
#include<stdio.h>
#include<string.h>
intmain(){
charstr1[12]="Hello";
charstr2[12]="World";
charstr3[12];
intlen;
/*copystr1intostr3*/
strcpy(str3,str1);
printf("strcpy(str3,str1):%s\n",str3);
/*concatenatesstr1andstr2*/
strcat(str1,str2);
printf("strcat(str1,str2):%s\n",str1);
/*totallenghthofstr1afterconcatenation*/
len=strlen(str1);
printf("strlen(str1):%d\n",len);
return0;
}

When the above code is compiled and executed, it


producesthefollowingresult
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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];

The structure tag is optional and each member


definitionisanormalvariabledefinition,suchasintior
floatforanyothervalidvariabledefinition.Attheendof
the structure's definition, before the final semicolon, you
can specify one or more structure variables but it is
optional. Here is the way you would declare the Book
structure
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
}book;

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

When the above code is compiled and executed, it


producesthefollowingresult
Book1title:CProgramming
Book1author:NuhaAli
Book1subject:CProgrammingTutorial
Book1book_id:6495407
Book2title:TelecomBilling
Book2author:ZaraAli
Book2subject:TelecomBillingTutorial
Book2book_id:6495700

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Booktitle:CProgramming
Bookauthor:NuhaAli
Booksubject:CProgrammingTutorial
Bookbook_id:6495407
Booktitle:TelecomBilling
Bookauthor:ZaraAli
Booksubject:TelecomBillingTutorial
Bookbook_id:6495700

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Booktitle:CProgramming
Bookauthor:NuhaAli
Booksubject:CProgrammingTutorial
Bookbook_id:6495407
Booktitle:TelecomBilling
Bookauthor:ZaraAli
Booksubject:TelecomBillingTutorial
Bookbook_id:6495700

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

one member for your program. The format of the union


statementisasfollows
union[uniontag]{
memberdefinition;
memberdefinition;
...
memberdefinition;
}[oneormoreunionvariables];

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;

Now, a variable of Data type can store an integer, a


floatingpointnumber,orastringofcharacters.Itmeans
asinglevariable,i.e.,samememorylocation,canbeused
tostoremultipletypesofdata.Youcanuseanybuiltinor
user defined data types inside a union based on your
requirement.
Thememoryoccupiedbyaunionwillbelargeenoughto
holdthelargestmemberoftheunion.Forexample,inthe
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

89/145

6/3/2016

CQuickGuide

above example, Data type will occupy 20 bytes of


memoryspacebecausethisisthemaximumspacewhich
can be occupied by a character string. The following
exampledisplaysthetotalmemorysizeoccupiedbythe
aboveunion
#include<stdio.h>
#include<string.h>

unionData{
inti;
floatf;
charstr[20];
};

intmain(){
unionDatadata;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}

When the above code is compiled and executed, it


producesthefollowingresult
Memorysizeoccupiedbydata:20

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
data.i:1917853763
data.f:4122360580327794860452759994368.000000
data.str:CProgramming

Here,wecanseethatthevaluesofi and f members of


http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

91/145

6/3/2016

CQuickGuide

union got corrupted because the final value assigned to


thevariablehasoccupiedthememorylocationandthisis
thereasonthatthevalueofstrmemberisgettingprinted
verywell.
Now let's look into the same example once again where
we will use one variable at a time which is the main
purposeofhavingunions
#include<stdio.h>
#include<string.h>

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

92/145

6/3/2016

CQuickGuide

data.i:10
data.f:220.500000
data.str:CProgramming

Here, all the members are getting printed very well


becauseonememberisbeingusedatatime.

CBitFields
Suppose your C program contains a number of
TRUE/FALSE variables grouped in a structure called
status,asfollows
struct{
unsignedintwidthValidated;
unsignedintheightValidated;
}status;

This structure requires 8 bytes of memory space but in


actual,wearegoingtostoreeither0or1ineachofthe
variables. The C programming language offers a better
waytoutilizethememoryspaceinsuchsituations.
Ifyouareusingsuchvariablesinsideastructurethenyou
can define the width of a variable which tells the C
compilerthatyouaregoingtouseonlythosenumberof
bytes.Forexample,theabovestructurecanberewritten
asfollows
struct{
unsignedintwidthValidated:1;
unsignedintheightValidated:1;
}status;
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

93/145

6/3/2016

CQuickGuide

The above structure requires 4 bytes of memory space


for status variable, but only 2 bits will be used to store
thevalues.
Ifyouwilluseupto32variableseachonewithawidthof
1 bit, then also the status structure will use 4 bytes.
Howeverassoonasyouhave33variables,itwillallocate
the next slot of the memory and it will start using 8
bytes.Letuscheckthefollowingexampletounderstand
theconcept
#include<stdio.h>
#include<string.h>
/*definesimplestructure*/
struct{
unsignedintwidthValidated;
unsignedintheightValidated;
}status1;
/*defineastructurewithbitfields*/
struct{
unsignedintwidthValidated:1;
unsignedintheightValidated:1;
}status2;

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

When the above code is compiled and executed, it


producesthefollowingresult
Memorysizeoccupiedbystatus1:8
Memorysizeoccupiedbystatus2:4

BitFieldDeclaration
Thedeclarationofabitfieldhasthefollowingforminside
astructure
struct{
type[member_name]:width;
};

The following table describes the variable elements of a


bitfield
Elements

Description

type

Anintegertypethatdetermineshowa
bitfield'svalueisinterpreted.Thetype
maybeint,signedint,orunsignedint.

member_name

Thenameofthebitfield.

width

Thenumberofbitsinthebitfield.The
widthmustbelessthanorequaltothe
bitwidthofthespecifiedtype.

The variables defined with a predefined width are called


bitfields.Abitfieldcanholdmorethanasinglebitfor
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

95/145

6/3/2016

CQuickGuide

example,ifyouneedavariabletostoreavaluefrom0to
7,thenyoucandefineabitfieldwithawidthof3bitsas
follows
struct{
unsignedintage:3;
}Age;

The above structure definition instructs the C compiler


thattheagevariableisgoingtouseonly3bitstostore
thevalue.Ifyoutrytousemorethan3bits,thenitwill
notallowyoutodoso.Letustrythefollowingexample
#include<stdio.h>
#include<string.h>
struct{
unsignedintage:3;
}Age;
intmain(){
Age.age=4;
printf("Sizeof(Age):%d\n",sizeof(Age));
printf("Age.age:%d\n",Age.age);
Age.age=7;
printf("Age.age:%d\n",Age.age);
Age.age=8;
printf("Age.age:%d\n",Age.age);
return0;
}

When the above code is compiled it will compile with a


http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

96/145

6/3/2016

CQuickGuide

warning and when executed, it produces the following


result
Sizeof(Age):4
Age.age:4
Age.age:7
Age.age:0

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;

By convention, uppercase letters are used for these


definitionstoremindtheuserthatthetypenameisreally
a symbolic abbreviation, but you can use lowercase, as
follows
typedefunsignedcharbyte;

Youcanusetypedeftogiveanametoyouruserdefined
datatypesaswell.Forexample,youcanusetypedefwith
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

97/145

6/3/2016

CQuickGuide

structure to define a new data type and then use that


datatypetodefinestructurevariablesdirectlyasfollows

#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;
}

When the above code is compiled and executed, it


producesthefollowingresult
Booktitle:CProgramming
Bookauthor:NuhaAli
Booksubject:CProgrammingTutorial
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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

A file represents a sequence of bytes, regardless of it


beingatextfileorabinaryfile.Cprogramminglanguage
provides access on high level functions as well as low
level (OS level) calls to handle file on your storage
devices.Thischapterwilltakeyouthroughtheimportant
callsforfilemanagement.

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);

Here, filename is a string literal, which you will use to


name your file, and access mode can have one of the
followingvalues
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);

The function fputc() writes the character value of the


argument c to the output stream referenced by fp. It
returnsthewrittencharacterwrittenonsuccessotherwise
EOF if there is an error. You can use the following
functionstowriteanullterminatedstringtoastream
intfputs(constchar*s,FILE*fp);

The function fputs() writes the string s to the output


streamreferencedbyfp.Itreturnsanonnegativevalue
on success, otherwise EOF is returned in case of any
error. You can use int fprintf(FILE *fp,const char
*format,...)functionaswelltowriteastringintoafile.
Trythefollowingexample.
Makesureyouhave/tmpdirectoryavailable.Ifitisnot,
thenbeforeproceeding,youmustcreatethisdirectoryon
yourmachine.

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);
}

When the above code is compiled and executed, it


creates a new file test.txt in /tmp directory and writes
twolinesusingtwodifferentfunctions.Letusreadthisfile
inthenextsection.

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

Both of these functions should be used to read or write


blocksofmemoriesusuallyarraysorstructures.

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

(#). It must be the first nonblank character, and for


readability, a preprocessor directive should begin in the
first column. The following section lists down all the
importantpreprocessordirectives
Directive

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

This directive tells the CPP to replace instances of


MAX_ARRAY_LENGTHwith20.Use#defineforconstants
toincreasereadability.
#include<stdio.h>
#include"myheader.h"

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

It tells the CPP to process the statements enclosed if


http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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__);
}

When the above code in a file test.c is compiled and


executed,itproducesthefollowingresult
File:test.c
Date:Jun22012
Time:03:36:24
Line:8
ANSI:1

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
CaroleandDebra:Weloveyou!

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
token34=40

It happened so because this example results in the


followingactualoutputfromthepreprocessor
printf("token34=%d",token34);

This example shows the concatenation of token##n into


token34 and here we have used both stringize and
tokenpasting.

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
Hereisthemessage:Youwish!

ParameterizedMacros
OneofthepowerfulfunctionsoftheCPPistheabilityto
simulate functions using parameterized macros. For
example,wemighthavesomecodetosquareanumber
asfollows
intsquare(intx){
returnx*x;
}

Wecanrewriteabovethecodeusingamacroasfollows

#definesquare(x)((x)*(x))

Macros with arguments must be defined using the


#definedirectivebeforetheycanbeused.Theargument
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

117/145

6/3/2016

CQuickGuide

list is enclosed in parentheses and must immediately


followthemacroname.Spacesarenotallowedbetween
themacronameandopenparenthesis.Forexample
#include<stdio.h>
#defineMAX(x,y)((x)>(y)?(x):(y))
intmain(void){
printf("Maxbetween20and10is%d\n",MAX(10,20));
return0;
}

When the above code is compiled and executed, it


producesthefollowingresult
Maxbetween20and10is20

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

The #include directive works by directing the C


preprocessor to scan the specified file as input before
continuing with the rest of the current source file. The
outputfromthepreprocessorcontainstheoutputalready
generated, followed by the output resulting from the
includedfile,followedbytheoutputthatcomesfromthe
text after the #include directive. For example, if you
haveaheaderfileheader.hasfollows
char*test(void);

and a main program called program.c that uses the


headerfile,likethis
intx;
#include"header.h"
intmain(void){
puts(test());
}

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

But as it grows, it becomes tedious, instead the


preprocessor offers the ability to use a macro for the
header name. This is called a computed include.
Insteadofwritingaheadernameasthedirectargument
of#include,yousimplyputamacronamethere
#defineSYSTEM_H"system_1.h"
...
#includeSYSTEM_H

SYSTEM_H will be expanded, and the preprocessor will


lookforsystem_1.hasifthe#includehadbeenwritten
that way originally. SYSTEM_H could be defined by your
MakefilewithaDoption.

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

Consider the following example where the cast operator


causes the division of one integer variable by another to
beperformedasafloatingpointoperation

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Valueofmean:3.400000

It should be noted here that the cast operator has


precedence over division, so the value of sum is first
converted to type double and finally it gets divided by
countyieldingadoublevalue.
Type conversions can be implicit which is performed by
thecompilerautomatically,oritcanbespecifiedexplicitly
through the use of the cast operator. It is considered
good programming practice to use the cast operator
whenevertypeconversionsarenecessary.

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Valueofsum:116

Here, the value of sum is 116 because the compiler is


doingintegerpromotionandconvertingthevalueof'c'to
ASCIIbeforeperformingtheactualadditionoperation.

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

The usual arithmetic conversions are not performed for


theassignmentoperators,norforthelogicaloperators&&
and ||. Let us take the following example to understand
theconcept

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Valueofsum:116.000000

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

So a C programmer can check the returned values and


can take appropriate action depending on the return
value.Itisagoodpractice,toseterrnoto0atthetime
ofinitializingaprogram.Avalueof0indicatesthatthere
isnoerrorintheprogram.

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
Valueoferrno:2
Errorprintedbyperror:Nosuchfileordirectory
Erroropeningfile:Nosuchfileordirectory

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Divisionbyzero!Exiting...

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);
}

When the above code is compiled and executed, it


producesthefollowingresult
Valueofquotient:4

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

allows you to call a function inside the same function,


thenitiscalledarecursivecallofthefunction.
voidrecursion(){
recursion();/*functioncallsitself*/
}
intmain(){
recursion();
}

The C programming language supports recursion, i.e., a


function to call itself. But while using recursion,
programmers need to be careful to define an exit
condition from the function, otherwise it will go into an
infiniteloop.
Recursive functions are very useful to solve many
mathematical problems, such as calculating the factorial
ofanumber,generatingFibonacciseries,etc.

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
Factorialof15is2004310016

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;
}

When the above code is compiled and executed, it


producesthefollowingresult
0

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);
}

It should be noted that the function func() has its last


argument as ellipses, i.e. three dotes (...) and the one
just before the ellipses is always an int which will
representthetotalnumbervariableargumentspassed.To
usesuchfunctionality,youneedtomakeuseofstdarg.h
header file which provides the functions and macros to
implement the functionality of variable arguments and
followthegivensteps
Define a function with its last parameter as
ellipses and the one just before the ellipses is
alwaysanintwhichwillrepresentthenumberof
arguments.
Create a va_list type variable in the function
definition. This type is defined in stdarg.h header
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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));
}

When the above code is compiled and executed, it


producesthefollowingresult.Itshouldbenotedthatthe
functionaverage()hasbeencalledtwiceandeachtime
thefirstargumentrepresentsthetotalnumberofvariable
arguments being passed. Only ellipses will be used to
passvariablenumberofarguments.
Averageof2,3,4,5=3.500000
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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

This function reallocates memory extending it


uptonewsize.

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];

But now let us consider a situation where you have no


idea about the length of the text you need to store, for
example,youwanttostoreadetaileddescriptionabouta
topic. Here we need to define a pointer to character
withoutdefininghowmuchmemoryisrequiredandlater,
basedonrequirement,wecanallocatememoryasshown
inthebelowexample

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);
}

When the above code is compiled and executed, it


producesthefollowingresult.
Name=ZaraAli
Description:ZaraaliaDPSstudentinclass10th

Same program can be written using calloc() only thing


isyouneedtoreplacemallocwithcallocasfollows
calloc(200,sizeof(char));

Soyouhavecompletecontrolandyoucanpassanysize
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

139/145

6/3/2016

CQuickGuide

value while allocating memory, unlike arrays where once


thesizedefined,youcannotchangeit.

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);
}

When the above code is compiled and executed, it


http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

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");
}
}

When the above code is compiled and executed with


singleargument,itproducesthefollowingresult.
$./a.outtesting
Theargumentsuppliedistesting

When the above code is compiled and executed with a


twoarguments,itproducesthefollowingresult.
$./a.outtesting1testing2
Toomanyargumentssupplied.

When the above code is compiled and executed without


passinganyargument,itproducesthefollowingresult.
$./a.out
Oneargumentexpected

It should be noted that argv[0] holds the name of the


program itself and argv[1] is a pointer to the first
commandlineargumentsupplied,and*argv[n]isthelast
argument.Ifnoargumentsaresupplied,argcwillbeone,
andifyoupassoneargumentthenargcissetat2.
Youpassallthecommandlineargumentsseparatedbya
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

143/145

6/3/2016

CQuickGuide

space, but if argument itself has a space then you can


pass such arguments by putting them inside double
quotes "" or single quotes ''. Let us rewrite above
example once again where we will print program name
and we also pass a command line argument by putting
insidedoublequotes
#include<stdio.h>
intmain(intargc,char*argv[]){
printf("Programname%s\n",argv[0]);

if(argc==2){
printf("Theargumentsuppliedis%s\n",argv[1]);
}
elseif(argc>2){
printf("Toomanyargumentssupplied.\n");
}
else{
printf("Oneargumentexpected.\n");
}
}

When the above code is compiled and executed with a


single argument separated by space but inside double
quotes,itproducesthefollowingresult.
$./a.out"testing1testing2"
Progranmname./a.out
Theargumentsuppliedistesting1testing2

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

Copyright 2016. All Rights Reserved.


Enter email for newsletter

http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

go

145/145

Vous aimerez peut-être aussi