0% found this document useful (0 votes)
852 views

C Programming Interview Questions and Answers - Static Variable in C

The keyword static is used to declare static variables in C. Static variables retain their value between function calls or program executions. They are initialized to zero by default and can only be initialized once. Static variables have file scope if declared globally and block scope if declared locally within a code block.

Uploaded by

Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
852 views

C Programming Interview Questions and Answers - Static Variable in C

The keyword static is used to declare static variables in C. Static variables retain their value between function calls or program executions. They are initialized to zero by default and can only be initialized once. Static variables have file scope if declared globally and block scope if declared locally within a code block.

Uploaded by

Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

8/14/2015

C programming Interview questions and answers: static variable in c

C programming Interview questions and answers

Clanguageinterviewquestionssolutionforfreshersbeginnersplacementtrickygoodpointersanswersexplanationoperatorsdatatypesarraysstructu
recursionpreprocessorsloopingfilehandlingstringsswitchcaseifelseprintfadvancelinuxobjectivemcqfaqonlinewrittentestprimenumbersArmstr
seriesfactorialpalindromecodeprogramsexamplesonc++tutorialsandpdf

Ctutorial

CProgrammingQuestions

CInterviewQuestions

CPrograms

CTest

Cprogrammingpdf

Programofc++

SqlServer

CQUESTIONSANDANSWERS
Cprogramexamples

Search

staticvariableinc

Cinterviewquestionsandanswers
Datatypequestions

LABELS

statickeywordinc:

Advancenc
Arrayinc

Variablenamingrulequestions
Operatorsquestions
Controlflowquestions

Keywordstaticisusedfordeclaringstaticvariablesin
c.Thismodifierisusedwithalldatatypeslikeint,float,
double,array,pointer,structure,functionetc.

Cprograms
C++
Datatypes
Exact

Switchcasequestions

Importantpointsaboutstatickeyword:

Functiontutori

Loopingquestions
Pointerquestions

1.Itisnotdefaultstorageclassofglobalvariables.For
example,analyzethefollowingthreeprogramsanditsoutput.

Stringquestions
Printf,Scanfquestions
Preprocessorquestions
Structurequestions
Commadlineargument
CquestionsinLinux
Conlinetest

Exampleofrecursioninc
Cprogrammingforums
CTUTORIAL
Memorymappingtutorialinc
Variablestutorialinc
Datatypestutorialinc
Storageclassestutorialinc
Loopingtutorialinc
Pointerstutorialinc
Functiontutorialinc
Arraytutorialinc
Preprocessortutorialinc
Advancedctutorial
POPULARPOSTS

Cprogramexamples|Interview
CompleteList

Java

linuxquestions
Loopinginc

(a)

MemoryMapp
Operators

#include<stdio.h>
inta
intmain(){
printf("%d",a)
return0
}

Cmixedpracticesets
Ctrickyquestions

FileHandling

pdf(11)
Pointers
Preprocessor
SQL

PAGEVIEWSL

7 2

Output:0

CLOVERCOM

(b)
#include<stdio.h>
staticinta
intmain(){
printf("%d",a)
return0
}

withGoogleFrie

Members

Output:0

Alreadyamemb

(c)
#include<stdio.h>
externinta
intmain(){
printf("%d",a)
return0
}
Output:Compilationerror
Atfirstglanceifyouwillobservetheoutputofabovethree
codesyoucansaydefaultstorageclassofglobalvariableis

http://www.cquestions.com/2011/02/static-variable-in-c.html

SUBSCRIBEV

Enteryoure

Deliveredb

STANDARDO
?

1/12

8/14/2015

C programming Interview questions and answers: static variable in c

Cinterviewquestionsandanswers
QUICKSORTUSINGCPROGRAM
Checkgivennumberisprimenumberor
notusingcprogram

static.Butitisnottrue.Why?Readexternstorageclass.
2.Defaultinitialvalueofstaticintegraltypevariablesare
zerootherwisenull.Forexample:

Writeacprogramtoreverseastring

#include<stdio.h>
staticcharc
staticinti
staticfloatf
staticchar*str
intmain(){
printf("%d%d%f%s",c,i,f,str)
return0
}

Mergesortprograminc

Output:000.000000(null)

CPROGRAMMINGQUESTIONSAND
ANSWER

3.Asamestaticvariablecanbedeclaredmanytimesbutwe
caninitializeatonlyonetime.Forexample:

Programtoconvertdecimaltobinaryin
c
Findouttheperfectnumberusingc
program
TOFINDFACTORIALOFANUMBER
USINGCPROGRAM
TOFINDFIBONACCISERIESUSINGC
PROGRAM

Vote

Votessofar:
Dayslefttovote

Cquestionsandanswers
Cinterviewquestionsandanswers
Debuggingquestionsincwithanswers
Aptitudequestionsandanswersinc
Cbasicquestions

Therewasanerrorinthisgadget

133

(a)
#include<stdio.h>
staticinti//Declaringthevariablei.
staticinti=25//Initializingthevariable.
staticinti//Againdeclaringthevariablei.
intmain(){
staticinti//Againdeclaringthevariablei.
printf("%d",i)
return0
}
Output:25
(b)
#include<stdio.h>
staticinti//Declaringthevariable
staticinti=25//Initializingthevariable
intmain(){
printf("%d",i)
return0
}
staticinti=20//Againinitializingthevariable
Output:Compilationerror:Multipleinitializationvariablei.
4.Wecannotwriteanyassignmentstatementglobally.For
example:
#include<stdio.h>
staticinti=10//Initializationstatement
i=25//Assignmentstatement
intmain(){
printf("%d",i)
return0
}

Output:Compilationerror
Note:Assigninganyvaluetothevariableatthetimeof

http://www.cquestions.com/2011/02/static-variable-in-c.html

2/12

8/14/2015

C programming Interview questions and answers: static variable in c

declarationisknownasinitializationwhileassigningany
valuetovariablenotatthetimeofdeclarationisknown
assignment.
(b)
#include<stdio.h>
staticinti=10
intmain(){
i=25//Assignmentstatement
printf("%d",i)
return0
}
Output:25
(5)Astaticvariableinitializesonlyonetimeinwhole
program.Forexample:
#include<stdio.h>
staticinti=10
intmain(){
i=5
for(i=0i<5i++){
staticinta=10//Thisstatementwillexecute
//onlytime.
printf("%d",a++)//Thisstatementwillexecute
//fivetimes.
}
return0
}
Output:1011121314
(6)Ifwedeclaredstaticvariablelocallythenitsvisibility
willwithinablockwhereithasdeclared.Forexample:
#include<stdio.h>
intmain(){
{
staticinta=5
printf("%d",a)
}
//printf("%d",a)variableaisnotvisiblehere.
return0
}
Output:5
7.Ifdeclaredastaticvariableorfunctiongloballythenits
visibilitywillonlythefileinwhichithasdeclarednotin
theotherfiles.Forexample:
(a)
#include<stdio.h>
staticfloata=144.0f//globaltoallfunction
intmain(){
{
printf("%d",a)//variableaisvisiblehere.
http://www.cquestions.com/2011/02/static-variable-in-c.html

3/12

8/14/2015

C programming Interview questions and answers: static variable in c

//printf("%d",b)variablebisnotvisiblehere.
}
printf("%d",a)//variableaisvisiblehere.
//printf("%d",b)variablebisnotvisiblehere.
return0
}
staticintb=5//Globaltoonlycalculationfunction
voidcalculation(){
printf("%d",a)//variableaisvisiblehere.
printf("%d",b)//variablebisvisiblehere.
}

(b)Consideracprogramwhichhaswrittenintwofilesnamed
asone.candtwo.c:
//one.c
#include<conio.h>
staticinti=25
staticintj=5
voidmain(){
clrscr()
sum()
getch()
}
//two.c
#include<stdio.h>
externinti//Declarationofvariablei.
externintj//Declarationofvariablej.
/**
Abovetwolineswillsearchtheinitializationstatementof
variableiandjeitherintwo.c(ifinitializedvariableis
staticorextern)orone.c(ifinitializedvariableis
extern)
*/
externvoidsum(){
ints
s=i+j
printf("%d",s)
}
Compileandexecuteabovetwofileone.candtwo.catthesame
time:
InTurboccompiler
Step1:Writeabovetwocodesinthefilenamedasone.cand
two.c(Youcangiveanynameasyoulike)andsaveit.
Step2:InTurboc++IDEclickonProject>Openprojectmenu
asshowninfollowingscreendump.

http://www.cquestions.com/2011/02/static-variable-in-c.html

4/12

8/14/2015

C programming Interview questions and answers: static variable in c

Step3:AfterClickingonopenprojectyouwillgetfollowing
screen:

InOpenprojectFiletextfieldwriteanyprojectnamewith
.prjextension.InthisexampleIamwritingprojectnameas
CProject.PRJ.NowpressOKbutton.
Step4:AfterpressingOKbuttonyouwillgetfollowing
screen:

http://www.cquestions.com/2011/02/static-variable-in-c.html

5/12

8/14/2015

C programming Interview questions and answers: static variable in c

NowclickonProject>Additemmenu.
Step5:AfterclickingAdditemyouwillgetfollowingscreen:

Inthenametextfieldwritedownallcsourcecodefileone
byonei.e.firstwriteone.candclickonAddbutton
Thenwritetwo.candclickonAddbuttonandsoon

http://www.cquestions.com/2011/02/static-variable-in-c.html

6/12

8/14/2015

C programming Interview questions and answers: static variable in c

Step6:AttheendclickonDonebutton.Afterclickingon
donebuttonyouwillgetfollowingscreen:

Atthelowerpartofwindowyoucanseeprojectname,listof
filesyouhaveaddedetc.
Step7:TocompilethetwofilespressAlt+F9andtorunthe
aboveprogrampressCtrl+F9
Note:ToclosetheprojectclickonProject>Closeproject.
Output:Compilationerror:Unknownsymboliandj.
Hencewecansayvariableiandjwhichhasinitializedinto
two.cisnotvisibleinfileone.c.Thisexampleproves
visibilityofgloballydeclaredstaticvariableisfile.
Note:Intheaboveexamplefunctionsumwhichwasdeclaredand
definedintwo.chasalsostorageclassextern.Sowecancall
fromotherfile(one.c).Ifitwillstaticthenwecannotcall
http://www.cquestions.com/2011/02/static-variable-in-c.html

7/12

8/14/2015

C programming Interview questions and answers: static variable in c

functionsumsincestaticstorageclassisonlyvisibletothe
filewhereithasdeclared.
(8)Ifwestaticvariablehasdeclaredlocallyorgloballyits
scopewillalwayswholetheprogram.Forexample:
(a)//locallydeclarationofstaticvariable
#include<stdio.h>
voidvisit()
intmain(){
inti=0
{//Openinginnerblock
staticinta=5//locallydeclaration
XYZ://Labelofgotostatement
printf("%d",a)
a++
i++
}//closinginnerblock.
visit()
/*printf("%d",a)Variableaisnotvisibleherebut
itisalive.*/
if(i<5)
gotoXYZ
return0
}
voidvisit(){

}
Output:56789
Explanation:Whenprogramcontrolwillcomeoutofinnerblock
wherevariableahasdeclaredthenoutsideofinnerblock
variableaisnotvisiblebutitsscopeisoutsidetheprogram
i.e.variableahasntdead.Ifwithhelpofgotostatement
controlagaincomesinsidetheinnerblockitprintsprevious
incrementedvalueswhichwasnotpossibleincaseofautoor
registervariables.
(b)
//Locallydeclarationsofvariable
Therearetwocsourcecodefiles:
//one.c
#include<stdio.h>
#include<conio.h>
voidmain(){
inti
for(i=0i<3i++){
{
staticinta=5
printf("%d\n",a)
a++
}
visit()
}
getch()
http://www.cquestions.com/2011/02/static-variable-in-c.html

8/12

8/14/2015

C programming Interview questions and answers: static variable in c

}
//two.c
#include<stdio.h>
voidvisit(){
printf("Dontdisturb,Iamlearningstorageclass")
/*printf("%d",a)Variableaisnotvisibleherebut
Itisalive.*/
}
Nowcompileandexecutebothfilestogether:
Output:
5
disturb,Iamlearningstorageclass
6
disturb,Iamlearningstorageclass
7
disturb,Iamlearningstorageclass
Explanation:Whencontrolgoestoanotherfileandcomeseven
thatvariabledidntdeadanditprintspreviousincremented
value.
Note:Inbothexamplesifyouwilldeclarestaticvariable
globallyyouwillgetsameoutput.

9.Astaticvariablesorfunctionshaveinternallinkage.An
internallinkagevariablesorfunctionsarevisibletothe
filewhereithasdeclared.
Introduction
auto
register
static
extern
Ctutorialhome.
+6 Recommend this on Google

21comments:
Aarti 2/18/11,12:11AM
explanationisjustfab.
Reply
Replies
akashrai 8/5/15,10:10PM
Butconceptsarewrong...plstrytoexecutetheprgyourselfuwillfindlotsoferror
Reply

Anonymous 6/16/11,12:23PM
In8thpoint(b)part,youhavecalledvisitinone.cfilebutintwo.cfileyouhavenotdeclaredtheexternkeyword
beforeitsdefination...canuplztelmewhy?
Reply

Anonymous 8/6/11,1:46PM

http://www.cquestions.com/2011/02/static-variable-in-c.html

9/12

8/14/2015

C programming Interview questions and answers: static variable in c


inthe8thpointwerlearningthescopeofstaticatoutsideofthefiles..
Reply

Anonymous 9/21/11,3:24PM
inthe8thpointthevisit()functionmustbedeclaredexternintwo.c.....correctmeifiamwrong..??
Reply
Replies
SimasA. 6/16/14,4:59PM
Allfunctionshaveexternasthedefaultstorageclass,sonoyoudon'tneedtowriteit.
Reply

dinhpq 10/13/11,11:14PM
Thanks.
Reply

Anonymous 11/18/11,1:08PM
reaalynice1....commendable
Reply

ranjith 1/2/12,4:59PM
#include
staticinti//Declaringthevariablei.
staticinti=25//Initializingthevariable.
staticinti//Againdeclaringthevariablei.
intmain(){
staticinti//Againdeclaringthevariablei.
printf("%d",i)
return0
}
Output:25

herifwecompileoutputweshouldget0only..beczinmainblocklocallyiofcoursestaticisnotinitialised...so
it intialissed by default as zero....comparing local and global local variable got more preference than global
staticvariable(i=25)..socompulsorywewillgetzeroasoutput....
plzcommenttothiscomment..toconformitcorrectanalysisornot
Reply
Replies
AnithaVenkatesan 1/26/13,3:16AM
Yathatscorrectactuallyitgivesoutputaso.

Vijai 2/11/14,9:05PM
YesyouarecorrectingccIdogetthesame.
vijay
Reply

urvinder 2/25/12,1:38AM
icheckedinvc++,itgivestheerrorwhilecompiling/**error'i':redefinitiondifferentstorageclass**/
Reply

Anonymous 2/25/13,8:58PM
thatwasacompletetutorial!!thanksbrother!!
Reply

http://www.cquestions.com/2011/02/static-variable-in-c.html

10/12

8/14/2015

C programming Interview questions and answers: static variable in c


AtiqurRahman 4/7/13,11:11AM
Thiscommenthasbeenremovedbytheauthor.
Reply

SALILAGRAWAL 12/24/13,12:02PM
SimilarArticleseeifitmakessense
StaticVariablesinC
Reply

karthiknayak 5/19/14,7:29PM
brilliantexplanation:D
Reply

pravin 9/2/14,11:22AM
yescorrect
Reply

AmitKumar 2/22/15,3:34PM
Whyitsgivingoutputas:43
Cananyonepleaseexplainittome?
Thanxinadvance?
#include
staticinti//Declaringthevariablei.
staticinti=25//Initializingthevariable.
staticinti//Againdeclaringthevariablei.
intmain(){
inti//Againdeclaringthevariablei.
printf("%d",i)
return0
}
Reply
Replies
NraVrs 3/4/15,5:59PM
inti//Againdeclaringthevariablei.
Thereisnostatickeywordinfrontofthedeclaration.Itis"another"i,anautomatic,uninitializedi.
Thecontentofthememoryareawhereitisplacedisaccidentally43.
Reply

RajNaik 6/15/15,3:02PM
3.Asamestaticvariablecanbedeclaredmanytimesbutwecaninitializeatonlyonetime.Forexample:
(a)
#include
staticinti//Declaringthevariablei.
staticinti=25//Initializingthevariable.
staticinti//Againdeclaringthevariablei.
intmain(){
staticinti//Againdeclaringthevariablei.
printf("%d",i)
return0
}
Output:25
HereOutputshouldbezero,not25.
Reply

http://www.cquestions.com/2011/02/static-variable-in-c.html

11/12

8/14/2015

C programming Interview questions and answers: static variable in c


MeenuRajput 7/31/15,10:32AM
Here,itgivesanoutput25butnotzerobecauseithasbeeninitializedas25althoughithasbeendeclared
againasalocalvariable.
Reply

Enteryourcomment...

Commentas:

Publish

HarikrishnaKodakanti(Google)

Signout

Notifyme

Preview

Linkstothispost
CreateaLink

NewerPost

Home

OlderPost

Subscribeto:PostComments(Atom)

[email protected].

http://www.cquestions.com/2011/02/static-variable-in-c.html

12/12

You might also like