What's new

Closed Basic Programming using C++ ----- 02 Variable Scope

Status
Not open for further replies.

fazz12

Honorary Poster
Joined
Aug 3, 2013
Posts
605
Reaction
291
Points
213
hello again mga ka PHC , ang topic po natin ngayon ay tungkol sa variable scope. in case hindi nyo pa po alam kung ano ang variable, you can see this post to know more about it:

Tutorial - Basic Programming using C++ ----- 01 Variables, Data Types | PHCorner Community

variable scope ang nagsasabi kung hanggang saan lang sa part ng code mo "nag eexist" ang isang variable. may dalawang uri ng scope ng variables, namely local scope at global scope.

global scope variable / global variable - magagamit at makikilala kahit saang part ng source code
local scope variable / local variable - magagamit lang kung saang scope sya dineclare.

consider this example:


[HASHTAG]#include[/HASHTAG] "stdafx.h"
[HASHTAG]#include[/HASHTAG] <iostream>
[HASHTAG]#include[/HASHTAG] <cstdlib>

int globalVarA; //variable with global scope. can be
//used anywhere within the source code. aka global variable

double globalVarB; //another global variable.

int main()
{
int localVarA; //a local variable. can only be used in function main()
float localVarB; //another local variable

globalVarA=5;
globalVarB=6.75;
localVarA=7;
localVarB=10;

std::cout<< "globalVarA: " << globalVarA << std::endl;
std::cout<< "globalVarB: " << globalVarB << std::endl;
std::cout<< "localVarA: " << localVarA << std::endl;
std::cout<< "localVarB: " << localVarB << std::endl;

system("pause");
return 0;
}

gaya po ng sabi sa comments ng code, magagamit po ang globalVarA at globalVarB kahit saang part ng source code, samantalang magagamit lang ang local var sa loob ng function main. hindi na makikilala ang localVarA at localVarB sa labas (outside ng '{' at '}' or scope symbols) ng function main.

for now hindi pa masyadong "nagmemake sense" yung about sa scope ng variables, kasi hindi pa po tayo dumadating sa lesson about functions. more about it later, ieexplain ko kung bakit hindi nakikilala ang mga local variables sa labas ng function kung saan sila idineclare. what you need to know right now is ang global variables na globalVarA at globalVarB ay nagamit natin sa loob (in between '{' and '}') ng function main, despite sa labas ng function main natin sila idineclare.
 
Last edited:
Dear fazz12,

Since 2 years have passed since the last reply in this thread, I am locking it to prevent necroposting. Feel free to start a new thread or contact any forum staff if you want this to be reopened.

Thread closed.
 
Status
Not open for further replies.

Similar threads

Back
Top