Search

1.4d — A first look at local scope

You already saw in the lesson 1.3 -- a first look at variables that when the CPU executes a statement like int x;, this causes the variable to be instantiated (created).

The natural follow-up question is, “so when is an instantiated variable destroyed?”

Appetite for destruction

A variable’s scope determines when a variable can be seen and used during the time it is instantiated. Function parameters and variables defined inside the function body both have local scope. That is, those variables can only be seen and used within the function that defines them. Local variables are created at the point of definition, and destroyed when they go out of scope (usually at the end of the function).

Here’s a simple example:

Here’s a slightly more complex example:

In function add(), parameters x and y are created when the function is called, can only be seen/used within function add(), and are destroyed at the end of the add() function.
Variable a and b are created within function main(), can only be seen/used within function main(), and are destroyed at the end of main().

To enhance your understanding, let’s trace through this program in a little more detail. The following happens, in order:

  • main() is executed
  • main’s variable a is created and given value 5
  • main’s variable b is created and given value 6
  • function add() is called with values 5 and 6 for parameters
  • add’s variable x is created and given value 5
  • add’s variable y is created and given value 6
  • operator + adds 5 and 6 to produce the value 11
  • add returns the value 11 to the caller (main)
  • add’s x and y are destroyed
  • main prints 11 to the console
  • main returns 0 to the operating system
  • main’s a and b are destroyed

And we’re done.

Note that if function add() were to be called twice, function add() parameters x and y would be created and destroyed twice -- once for each call. In a program with lots of functions, variables are created and destroyed often.

In the above example, it’s easy to see that variables a and b are different variables from x and y.

Now consider the following program:

In this example, all we’ve done is change the names of variables a and b inside of main() to x and y. This program still runs fine, even though both main() and add() both have variables named x and y. Why does this work?

First, we need to recognize that even though main() and add() both have variables named x and y, these variables are distinct. The x and y in main() have nothing to do with the x and y in add() -- they just happen to reuse the same names.

Second, when inside of main(), the names x and y refer to the locally scoped variables x and y. Those variables can only be seen (and used) inside of main(). Similarly, when inside function add(), the names x and y refer to function parameters x and y, which can only be seen (and used) inside of add().

In short, neither add() nor main() know that the other function has variables with the same names, and it’s always clear to the compiler which x and y are being referred to at any time. This means that functions don’t need to know or care what other functions name their variables, which is fantastic for us because it makes life easy.

We’ll talk more about local scope, and other kinds of scope, in chapter 4.

Rule: Names used for function parameters or variables declared in a function body are only visible within the function that declares them.

Quiz

1) What does the following program print?

Quiz answers

1) Show Solution

1.5 -- A first look at operators
Index
1.4c -- Keywords and naming identifiers

81 comments to 1.4d — A first look at local scope

  • Liang

    Thanks for continuously maintaining this site! Is there any plan to making everything in a single PDF file?

  • Amin

    i still dont get it whats return 0?
    thank you

    • Alex

      I talk about return values in section 1.4 -- a first look at functions.

      Every executable returns a value to the operating system that indicates whether the executable ran correctly or had an error. The return value of main() is used for this purpose. When main() returns 0, (by convention) it means “the program ran okay!”. If main returns a non-zero number, (again, by convention) that means something went wrong.

  • Maxim

    You forgot to write a " using namespace" in the first example)

  • sanchit shetye

    I am confused between above quiz code snippet and last 1.4a question 1 code snippet.
    why there compilation failed at void returns nothing and here its compiled well.
    pls clarify i am new to C++.

    • Alex

      A return type of void means the function doesn’t return anything. The example in section 1.4a quiz question 1 looks like this:

      This function is trying to use a return statement to return a value, even though the function has a void return type. That’s not allowed.

      In this quiz, there’s also a function with no return type:

      But the function doesn’t have a return statement, so it isn’t trying to return anything at all. It just executes the lines in the functions and returns to the caller. No value is passed back. That’s fine, so the compiler doesn’t complain.

  • Daniel

    Hello,

    Could you please explain how x is given a value of 1 in the function doIt()?

    Cheers

    Daniel

    • Alex

      The calling function (main) passes in a value of 1 when the function is called. However, the function assigns the value of 3 to this variable shortly thereafter.

  • Erick

    I friggin love this site! This is the first time I truly understand this stuff. You should write a book!

  • Simon

    How come doIt doesn’t come up as an error when you compile? If the value was only declared in Main() and doesn’t affect other functions, shouldn’t we declare the variable in doIt too? Otherwise wouldn’t it change Main()’s value for x?

  • Ben

    I can’t seem to compile the exercise, it’s giving me an error.

    1>LINK : fatal error LNK1168: cannot open D:Visual StudioProjectsAnotherTryConsoleApplication1DebugConsoleApplication1.exe for writing
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Double-checked my code, even copy-pasted from here.
    Doesn’t want to run either way.
    On Visual Studio 2013

    • Alex

      For things like this (which aren’t C++ problems, but are more likely related to your OS or other applications), Google is your best friend. Try searching for LNK1168.

      Here’s one possibility: http://gauravpandey.com/wordpress/?p=291.

      • Ben

        I feel so stupid now.
        Didn’t even think of searching it on Google,
        even though I use it every day.

        Problem solved, thank you so much for your reply.

        The effort you put into this tutorial and the comment section is really, really appreciated as well.

  • Thank you so much!! I have struggled with some of this but have always gotten the answers to those pesky problems. You are much appreciated.

  • Sam

    Hello Alex,

    Question regarding the quiz 1 (1.4b).
    When the function call for the doit passes the value of x=1 does doit() overwrite the value as the value of x is being declared locally ?
    I am just wondering what happens to the parameter passed doit(x), while the function call is made. why does the output print x= 3 and y =4 while executing the function call doit().

    Thanks

  • Simon

    In the comments at the

    lines you state that variables declared within main are created there.  They are not actually created until the lines where they get declared.  Referring to the variables before those lines would result in a compiler error.

    Many thanks for the tutorial.  I’ve enjoyed it thus far.

    • Alex

      This is a tricky topic, and one in which we need to be careful of what we mean by “created”.

      There are two related concepts here that we should differentiate between: When a variable is allocated in memory, and when it is usable (visible) in your code.

      It turns out that when memory allocation for local variables works is compiler dependent. However, most compilers allocate memory for all of the local variables in a block when the block is entered, not when the variable is actually defined in the code. This is typically done for performance reasons, because it’s easier and more efficient to do all of the allocations at once rather than incrementally as they are needed.

      However, those variables aren’t usable in your code until after the point where the variable has been declared. This is enforced by the compiler at compile time.

      You can see that Visual Studio does the allocation at the start of the block with the following experiment:

      When you run the above code in a debugger and stop at the breakpoint, you can put a watch on “&x” (the address of x) and see that variable x has already been given an address, even though the line of code where x is defined hasn’t been executed yet. This supports the conclusion that Visual Studio is allocating all variables at the top of the block (otherwise variable x wouldn’t have an address until the line “int x = 5” was executed).

  • Thorax

    First of all thanks for these tutorials. They are a massive help. I can’t thank you enough.

    I can’t get my head around this.

    Why the the x declared this way, and the y declared differently?

    In my mind, either of these should do basically the same thing.

    But obviously neither work. I assume it has something to do with the function being of void type. But I honestly have no idea.

    I understand the answer to the quiz, but I just can’t understand why these other ways wouldn’t work.

    Thanks a lot! Much appreciated!

    • Alex

      To understand this, it’s important to understand the difference between a local variable and a function parameter. They are actually very similar!

      Let’s start with y first. In the example above, you’ve declared “int y = 4”. When this line of code is executed, memory will be allocated for an integer variable named y, and the value 4 will be assigned to y. Because y is a local variable, y will be destroyed at the end of the function.

      Now let’s look at x. You’ve declared “int x” as a function parameter. When this line of code is executed, memory will be allocated for an integer variable named x, and the value passed in by the caller will be assigned to x. Because x is a function parameter, x will be destroyed at the end of the function.

      So essentially, the primary difference between x and y is the fact that x takes its value from the function caller, where as y does not (in this case, the value assigned to y is defined inside the function itself).

      The fact that the function returns void just means the function returns no value to the caller. It doesn’t have anything to do with how the variables are declared or assigned values.

      So let’s take a look at the two functions you’ve written:

      In this case, when the function is called, variable x would be allocated and assigned the value 3. Then variable y would be allocated and assigned the value 4. Then both would be destroyed, and the function would return to the caller without doing anything useful.

      In this case, when the function is called, x and y would be allocated and assigned the values passed to the function from the caller. Then the function would overwrite those values with the values 3 and 4, respectively. Then the function would return to the caller without doing anything useful.

      • Ed

        This is my question really. I don’t understand why, in the last two examples, the function doesn’t do anything useful, but in the first example it works.

        • Alex

          Not sure what you mean. Both of the functions in the comment above “work” (in that they compile) but are “useless” (in that they don’t do anything useful).

        • George

          I think you are getting confused with what actually needs to work. All 3 options we’ve just seen "work" as Alex said above, the point is however that in the original example the code actually outputs something in the function and therefore is useful. I’m pretty sure you could put the same output line below all 3 options and make them all useful.

  • zhiwei

    Thanks so much !The tutorial is AWESOME!!!! And you are really very patience to answer the question so far!!

  • in short sir, you are saying that we can use a same variable for two different values? Right?
    Your are awesome! Correct me if m wrong. 🙂

    • Alex

      A given variable can only hold one value at a time. However, you can change the current value of a given variable by assigning a new value to it. You can change the value in this way as many times as you like.

  • bobz

    Hi, Alex

    I am stuck on your 16 line program at the top of this section.  Below I have copied your listing of what happens, followed by my comments or questions.

    •main() is executed OK
    •main’s variable a is created and given value 5 OK
    •main’s variable b is created and given value 6 OK
    •function add() is called with values 5 and 6 for parameters  
    Where? Is that in line 14?
    •add’s variable x is created and given value 5  
    I see where x and y are created in line 3 but I do not see where values are assigned?
    •add’s variable y is created and given value 6
    I see where x and y are created in line 3 but I do not see where values are assigned?
    •operator + adds 5 and 6 to produce the value 11  OK
    •add returns the value 11 to the caller (main) OK
    •add’s x and y are destroyed OK
    •main prints 11 to the console OK
    •main returns 0 to the operating system OK
    •main’s a and b are destroyed OK

    I am confused by the substantially different treatment between (a,b) and (x,y).  Why is this?
    For example, x and y are "created" while a and b are "initialized".  Why the difference?
    X and y are added in a "return" statement, while a and b are added in a standard library cout statement.  Why the difference?
    (a,b,x,y) are all described as variables; none as parameters, so that would not explain the differing treatment.  All 4 variables are described as being usable "within this function only."

    What determines the execution order that you describe?

    Thanks,

    BobZ

    • Alex

      Add() is called with values 5 and 6 for parameters on line 14. This is the “add(a, b)” part of the statement.
      x and y are created on line 3, and assigned 5 and 6 from the parameters that were passed into the function on line 14.

      a, b, x, and y are all similar. The only difference is that variables a and b are created within the function, where as variables x and y are function parameters, meaning that the caller is responsible for giving them values.

      x and y are returned by the function back to the caller so that the caller can do whatever it wants -- in this case, print the sum.

      The execution order starts at the top of main() and proceeds linearly through each line of code until the call to add() is reached. At this point, execution of main() is interrupted and add() is executed linearly until the return statement is reached. The control returns back to main(), and the code in main() executes line by line until the end of main() is reached.

  • bobz

    OK; I have been struggling to make sense of this on and off for over a week.

    In one place we are adding x and y and in the other we are adding a and b.  I do not understand how these two are considered by the compiler to be the same addition, especially since x and y are destroyed after being returned?

    Further; what is the significance of "return x + y;"?  Are we actually adding them here or are we just "returning" both of them? I would think that it would be redundant to add them in that return statement.     What if this statement said "return x,y;"?   It would be great to see a comment after that statement telling me exactly what it does.

    For some reason this lesson has not been connecting for me and I appreciate your patience.

    • Alex

      Note that we never _directly_ add variables a and b. We pass the values of variable a and b to function add(), which puts those values in variables x and y. The function add() uses the + operator to add x and y, and this result (11) is returned to main() which prints it.

      Let’s take a look at a slightly modified example that does the exact same thing as the original example, just with a few extra intermediate steps:

      “z = x + y” does two things: First, it evaluates x + y, which uses the + operator to add the values of x and y (5 and 6) to produce the sum of 11. This value is then assigned to variable z. This is where the actual addition happens.

      “return z” then returns this value (11) back to the caller (main), which can do whatever it wants with that value. In this case, main() assigns it to variable c, and then prints the value of c.

      In the above example, both variables z and c are extraneous, since they are only used as intermediate values. In the original example, we “optimized” them out.

      If the return statement said “return x,y” then “x,y” would be evaluated. The comma operator discards the first operand and returns the second operand. So “x, y” evaluates to y, which in this case is 6. The value of 6 would then be returned to the caller (main).

      I’d suggest printing the above snippet of code and then drawing arrows showing how the data flows. There should be an arrow connecting a to x, b to y, and the return value of add() to c.

  • bobz

    Hi, Alex

    Thanks for your continued help.  One thing I did not know was whether "add" was a term which is defined within the compiler or whether we are defining it however we want?  So after compiling and running your example above, I changed "add" (on line 3 only) to "adg" and compiled/ran again.  That produced errors.  So far so good. From that point I further changed "add" on line 17 to "adg" (so now both lines 3 and 17 have "adg" instead of "add") and compiled/ran again.  The code compiled and executed as your original; no errors.  This tells me that "add" (or "adg" for that matter) is a user defined function; right?

    Then I changed the "+" sign in line 5 to "*".  As I hoped, it compiled and ran OK, and the console displayed a value of 30.  So far, so good.

    Then I changed the "+" -> "*" sign in line 5 to "/".  It compiled and ran OK, and the console displayed a value of 0.  Of course z is defined as an integer and now I am feeding it a fractional value.  I guess it rounds down?  When I then swapped the values so a = 6 and b = 5, the console displayed a value of 1.  Sorry maybe this is getting off the topic.

    I am not sure that I have this all figured out yet.  But understanding that "add" has no intrinsic meaning (that I am defining it) will probably help.

    I know that programming (like electronic circuit design with which I am much more experienced) can fail due to tiny nitpick errors.  So if I have said anything that is a tiny bit wrong please let me know.

    Thanks again.

    BobZ

    • Alex

      Yes! add() is a user defined function. As the user, we’ve defined it like this:

      I applaud your use of experimentation to determine that!

      Integer division doesn’t round down, it drops all fractional values (in mathematical terms, it takes the floor of the result). I cover that topic in the next section in the lesson on integers.

  • bobz

    Hi, Alex

    Been stuck on 1.4b for a while, but just now I attempted the quiz and got it right so I’ve decided to move on to your next "episode."

    Thanks,

    BobZ

  • Ryan Lee

    Hey I was curious as to why the main x and y variables aren’t also used in add. I mean I get the concept and that it works fine, but in your explanation you say that the main function variables are LOCAL to main. Add is called in the main function, so does that mean it is then included in the locality? I was wondering if it is still seen as separate but just called upon entity that is essentially immune to the variable calls in main by having its own locality?

    • Alex

      Even though add() is called by main(), add has its own sense of locality that is separate from main(). That’s why it uses its own parameters -- it doesn’t have access to x and y.

  • This all makes sense to me except for one step. In the quiz why are we passing along the parameter of x (which equals 1) to doIt?

    It doesn’t seem to be used at all. Here is the order of events listed in the answer:

    doIt() is called with parameter 1
    doIt’s variable x is created and given value 1
    doIt’s variable x is assigned the value 3

    Seems like it would work the same if we did this:

    Am I correct or am I missing something? What is the purpose of sending that parameter to the doIt function?

    Thanks!

  • de_sk

    so far so good loving it…tnx Alex
    my first simple integer calculator 🙂

    // This simple integer calcuator helps to do addition, subtraction, division and multipilication of two integer numbers.

    code

    #include "stdafx.h"
    #include <iostream>

    int main()
    {
        using namespace std;
        int x;
        int y;

        // Addation
        cout << "Addition!!" << endl;
        cout << "Please Enter First Integer Number: ";
        cin >> x;
        cout << "Please Enter Second Integer Number: ";
        cin >> y;
        cout << "Addtion of two Integer Number is: " << x + y << endl << endl;

        // Subtraction

        cout << "Subtraction!!" << endl;
        cout << "Please Enter First Integer Number: ";
        cin >> x;
        cout << "Please Enter Second Integer Number: ";
        cin >> y;
        cout << "Addtion of two Integer Number is: " << x - y << endl <<endl;
        
        // Multiplication
        cout << "Multipicaion!!" << endl;
        cout << "Please Enter First Integer Number: ";
        cin >> x;
        cout << "Please Enter Second Integer Number: ";
        cin >> y;
        cout << "Addtion of two Integer Number is: " << x * y << endl << endl;

        // Division

        cout << "Division!!" << endl;
        cout << "Please Enter First Integer Number: ";
        cin >> x;
        cout << "Please Enter Second Integer Number: ";
        cin >> y;
        cout << "Addtion of two Integer Number is: " << x / y << endl <<endl;

        cout << "Summary: " << endl;
        cout << "Additon       : " << x << " + " << y << " = " << x + y << "   " << "Subtracton: " << x << " - " << y << " = " << x - y << endl;
        cout << "Multipication : " << x << " * " << y << " = " << x * y << "   " << "Division  : " << x << " / " << y << " = " << x / y << endl << endl;
        return 0;
        
    }
    /code

    • Rehan Ullah Afridi

      Nice Indeed! It could be more fine if you used float instead of int. In that case, long numbers and also numbers with decimals would be calculatable. Another thing as our teacher Alex has said, it would be good to use different functions for addition, subtraction etc. I have also made same thing like you! Awesome!! and by the way use

      for web formatting lol!!

  • Andile

    Hi Alex, brilliant tutorials. I see they date way back but you still maintain the site - props to you. Tell me, do you not have video tutorials? sometimes i’m in a press for time and it takes a whole lot longer to read than to watch a video

  • MarkH

    I love these tutorials, but the two examples here confuse me.

    In the first example you wrote this:

    In the second example you wrote this:

    The code is the same; why is only x created/destroyed in the second example?

  • Michael Doherty AKA TechBayTed

    Absolutely the best book/tutorial I’ve come across - ever. It is superb for reheating long forgotten tech college/university programming skills and best practice. Thanks a lot!!!

  • Inam

    Can you explain what happened in this program?Ima bit confused.

    • Alex

      Sure. main() defines two variables: x (initialized with value 5) and y (initialized with value 6). main() then calls print(x, y), which evaluates to print(5, 6).

      print’s x parameter gets initialized with the value 5, and print’s y parameter gets initialized with the value 6. print() then asks the user to enter new values for x and y. These new values are then added together and returned back to main(), who prints them.

  • Inam

    What do you mean by the word destroyed is that the program is reseted to its previous condition, right?

    • Alex

      Variables that are destroyed no longer exist. You can’t access them through that identifier any more.

    • Hesam

      first of all many thanks to Alex for every thing.
      It is worth to see How I changed your codes a bit to make it possible a better undestanding of the sitation.
      #include "stdafx.h"
      #include <iostream>

      int print(int x,int y)
      {
          std::cout << "input x";
          std::cin >> x;
          std::cout << "input y";
          std::cin >> y;
          return x+y;
      }

      int main()
      {
          int x=5;
          int y = 6;

          std::cout << "x+y="<<print(x,y) << std::endl;
          std::cout<<"x+y="<<x+y<<std::endl;
          return 0;
      }

  • Annibale

    I am not sure I understand the comments inside your program. I am quite new at programming and I am probably making a mistake. At some point you write

    I would rather say that

    In order to distinguish creation and initialization of the variables, I would write

    Am I wrong? Did I miss something? Thanks for your answer!

    • Alex

      How can a and b created in more than one place?

      • Darren

        Oh no! I think were straying into philosophy or maybe quantum physics or possibly both…

        Anyway, creation <=> initialisation. In other words an object *is* created when it is initialised, and when it is initialised it is created. Boom! [drop mic, leave room, outta here].

  • Anze

    Hi! Just a small thing to clarify, that helps me with my logic. It’s regarding your answer
    to the assignment.

    Here’s what happens in this program:

    main() is executed
    main’s variable x is created and given value 1
    main’s variable y is created and given value 2
    cout prints “main: x = 1 y = 2”
    doIt() is called with parameter 1
    doIt’s variable x is created and given value 1
    doIt’s variable x is assigned the value 3
    doit’s variable y is created and given value 4
    cout prints “doIt: x = 3 y = 4”
    doIt’s x and y are destroyed

    OK. As far as I understood the order, after the line "doIt’s variable x is assigned the value 3", it should be
    doit’s variable y is created and given value 2 //not 4//
    doIt’s variable y is assigned the value 4

    Please correct me if I am wrong, but as far as I understood this lesson, first the variable of the main function is created (and given value) and then the value of the function that is called is assigned to the variable. Correct?

    • Alex

      Not quite. Note that the value of 2 was assigned to main’s variable y. The variable y in doIt() is an entirely different variable. main’s y and doIt’s y do not intersect or share data.

      Note that when we call doIt(x), the value of variable x (1) is passed as an argument to function doIt(), so we’re calling doIt(1).

      Now look at the parameters for function doIt. In this case, the parameter for function doIt is also named x (a different x than main’s x). Therefore, doIt’s x is assigned the value of the argument passed in (1). At this point, doIt’s y has not even been created yet, because it is not part of the parameter list.

      When y is created, it will be initialized with the value of 4, as indicated by the line “int y = 4” inside doIt(). While we’re inside doIt(), what happened previously inside main is of no consequence.

  • Anze

    Ok thanks for the reply, I just needed time to get over it once again.
    I can’t say I got it, but it seems that the whole point right now is that even though
    doIt creates different value for variable x, "it doesn’t matter to main", because
    the main still uses x and y variables from the main, because the variables of main and doIt don’t mix-
    they don’t "see each other".

    I have no clue about programming, so I am sorry for my stupid questions and thanks for the smart answers.

  • Trev

    Line 15: Why is doIt printed to console with no std::cout?Thnks

    • Alex

      doIt() is a function call. When the code gets to to line 15, it jumps to line 3, executes lines 3-8, and then returns back to line 16.

      The “doIt” output is printed on line 7 using std::cout.

  • harshahemanth

    Alex tell the last answer for this above questions in simple way

    • Alex

      I’m not sure what you mean. Are you asking for more detail about the answer to the quiz question? The answer steps through what happens. Is there something in particular you don’t understand?

  • Lampros Papalampros

    alex which is the font your are using for code? I cannot find a satisfactory font. I am leaning towards Consolas but I am not ok. 1Il are very similar and yours font looks ideal

  • Mohamed

    thnx for this website

  • pandaMax

    Hey there! Just saw a little repetition in the explanations. At "Local scope prevents naming collisions", juste below the exemple, the sentence "Because x and y in main() have local scope, add() can’t see them." is written twice in a row.

    Thanks for your hard work!

  • MechanicNeurons

    /*
    Alex. I hope you are earning well, I hope you are happy. I don’t know you but I believe that you deserve a beautiful life.
    */

  • Jim

    Alex,

    I’m rereading this lesson and I noted that you didn’t mention that curly braces limit the scope of all local variables in C++. That’s surprising since you didn’t mention them at all. Why? This is the ideal lesson to teach this in?

    • Alex

      This section is just a first look. I haven’t yet talked about what a block is, or how nested blocks work, so it’s a bit difficult to explain without that. I cover this in more detail in chapter 4.

  • Hariharan

    Hey,the tutorial is really efficient and friendly.But please try to work with the ease of navigation.Currently its section 1.4 right,so it’ll be much better if you could provide a next and previous button so that the user can go through the stuffs sequentially.Table of contents on the left hand side will also suffice.

  • Ed

    Hi Alex

    Thanks for these tutorials, they’re great.

    For the question example:

    Is it necessary to put (int x) in void doIt(int x) at the start?

    Cant you set the function to automatically take the values for x and y specified within, without having to take 1 for x first and change it to 3?

    • Alex

      No, it’s not necessary -- in fact, it would be better to declare x as a local variable inside the function (like y is) since the argument passed in is never used. But the point here is to make sure you understand how function parameters work at a basic level.

  • My dear c++ Teacher,
    Please let me make a remark.In second program’s comments you are referred to variable x only.
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me add to quiz code, variable z = 5, and doIt(z), as follows:

    It works fine.
    With regards and friendship.

  • My dear c++ Teacher,

    Please let me explain the reason I consider you my c++ Teacher. It is that you explain exactly how a program works. For example, regarding program in quiz you state:
    "   main() is executed
        main’s variable x is created and given value 1
        main’s variable y is created and given value 2
        cout prints “main: x = 1 y = 2”
        doIt() is called with parameter 1
        doIt’s variable x is created and given value 1
        doIt’s variable x is assigned the value 3
        doit’s variable y is created and given value 4
        cout prints “doIt: x = 3 y = 4”
        doIt’s x and y are destroyed
        cout prints “main: x = 1 y = 2”
        main returns 0 to the operating system
        main’s x and y are destroyed

    Note that even though doIt’s variables x and y had their values assigned to something different than main’s, main’s were unaffected."

    With regards and friendship.

  • Devil Hand

    Does the variables x and y have different memory locations for different functions?
    If two different memory locations have the same name at one time, then how does the compiler knows which value to use?
    Does this has to do something with pointers?

    • Alex

      The memory locations for x and y will be distinct not only for different functions, but also for each function call! Consider the case where a function calls itself (this is called recursion). In such a case, the x and y for each function call had better be distinct, or one call to the function would step on the values from the previous call. We’ll talk about this more in chapter 7.

      If it’s ever the case that two variables (or functions) with the same name are in scope (can be used) at the same time, then you have a possible naming conflict. In some cases, there are precedence rules that govern which will get used. But if the compiler can’t decide, it will give you a compile error and ask you to disambiguate. Fortunately, C++ contains a lot of ways to avoid this, so it doesn’t happen very often as long as you follow best practices.

      This has nothing to do with pointers.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter