1. Welcome to PHCorner Forums. Take a moment to Sign up and gain unlimited access and extra privileges that guests are not entitled to, such as:

    All that and more! Registration is quick, simple and absolutely free. Join our community today!

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

Discussion in 'Coding, Programming' started by fazz12, Mar 6, 2015.

  1. fazz12

    fazz12 Addict Established

    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:

    Please or Register to view links

    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: Mar 6, 2015
    shivnta2002 likes this.
  2. DCCS

    DCCS Forum Veteran Established

    Keep sharing (y)
     
    fazz12 likes this.
  3. fazz12

    fazz12 Addict Established

    thanks bossing :D:D
     
  4. DCCS

    DCCS Forum Veteran Established

    Your welcome bro. ;)
     
    fazz12 likes this.
Tags / Keywords: