2.4 — Introduction to local scope

Local variables

Function parameters, as well as variables defined inside the function body, are called local variables (as opposed to global variables, which we’ll discuss in a future chapter).

In this lesson, we’ll take a look at some properties of local variables in more detail.

Local variable lifetime

In lesson 1.3 -- Introduction to variables, we discussed how a variable definition such as int x; causes the variable to be instantiated (created) when this statement is executed. Function parameters are created and initialized when the function is entered, and variables within the function body are created and initialized at the point of definition.

For example:

The natural follow-up question is, “so when is an instantiated variable destroyed?”. Local variables are destroyed in the opposite order of creation at the end of the set of curly braces in which it is defined (or for a function parameter, at the end of the function).

Much like a person’s lifetime is defined to be the time between their birth and death, an object’s lifetime is defined to be the time between its creation and destruction. Note that variable creation and destruction happen when the program is running (called runtime), not at compile time. Therefore, lifetime is a runtime property.

For advanced readers

The above rules around creation, initialization, and destruction are guarantees. That is, objects must be created and initialized no later than the point of definition, and destroyed no earlier than the end of the set of the curly braces in which they are defined (or, for function parameters, at the end of the function).

In actuality, the C++ specification gives compilers a lot of flexibility to determine when local variables are created and destroyed. Objects may be created earlier, or destroyed later for optimization purposes. Most often, local variables are created when the function is entered, and destroyed in the opposite order of creation when the function is exited. We’ll discuss this in more detail in a future lesson, when we talk about the call stack.

Here’s a slightly more complex program demonstrating the lifetime of a variable named x:

In the above program, x’s lifetime runs from the point of definition to the end of function main. This includes the time spent during the execution of function doSomething.

Local scope

An identifier’s scope determines where the identifier can be accessed within the source code. When an identifier can be accessed, we say it is in scope. When an identifier can not be accessed, we say it is out of scope. Scope is a compile-time property, and trying to use an identifier when it is not in scope will result in a compile error.

A local variable’s scope begins at the point of variable definition, and stops at the end of the set of curly braces in which they are defined (or for function parameters, at the end of the function). This ensures variables can not be used before the point of definition (even if the compiler opts to create them before then).

Here’s a program demonstrating the scope of a variable named x:

In the above program, variable x enters scope at the point of definition and goes out of scope at the end of the main function. Note that variable x is not in scope anywhere inside of function doSomething. The fact that function main calls function doSomething is irrelevant in this context.

Note that local variables have the same definitions for scope and lifetime. For local variables, scope and lifetime are linked -- that is, a variable’s lifetime starts when it enters scope, and ends when it goes out of scope.

Another example

Here’s a slightly more complex example. Remember, lifetime is a runtime property, and scope is a compile-time property, so although we are talking about both in the same program, they are enforced at different points.

Parameters x and y are created when the add function is called, can only be seen/used within function add, and are destroyed at the end of add. Variables 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 of how all this fits together, let’s trace through this program in a little more detail. The following happens, in order:

  • execution starts at the top of main
  • 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 arguments
  • add‘s variable x is created and initialized with value 5
  • add‘s variable y is created and initialized with value 6
  • operator+ evaluates expression x + y to produce the value 11
  • add copies the value 11 back to caller main
  • add‘s y and x are destroyed
  • main prints 11 to the console
  • main returns 0 to the operating system
  • main‘s b and a are destroyed

And we’re done.

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

Functional separation

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 similar program:

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

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

Second, when inside of function main, the names x and y refer to main’s 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. Because the scopes don’t overlap, it’s always clear to the compiler which x and y are being referred to at any time.

Key insight

Names used for function parameters or variables declared in a function body are only visible within the function that declares them. This means local variables within a function can be named without regard for the names of variables in other functions. This helps keep functions independent.

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

Where to define local variables

Local variables inside the function body should be defined as close to their first use as reasonable:

In the above example, each variable is defined just before it is first used. There’s no need to be strict about this -- if you prefer to swap lines 5 and 6, that’s fine.

Best practice

Define your local variables as close to their first use as reasonable.

Quiz time

Question #1

What does the following program print?

Show Solution

2.5 -- Why functions are useful, and how to use them effectively
2.3 -- Introduction to function parameters and arguments

191 comments to 2.4 — Introduction to local scope

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

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

  • 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].

  • 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;
          return 0;

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

  • 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!!!

  • 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?

  • 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

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


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

    • 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!!

  • 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?


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

  • 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."



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


    • 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

    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

    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?



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

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

  • zhiwei

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

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

  • 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).

  • 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().


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

  • 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:

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

  • 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?

  • Erick

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

  • Daniel


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



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

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

  • Maxim

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

    • Alex

      Fixed. Thanks for the heads up.

      • Tom

        i've been following the tutorial up to now, and when using Visual Basic, I get errors when i write "using namespace" at the top. I use both headers as you have listed in your examples and it works perfectly without im wondering why I'm getting that issue, particularly with 'std::cout'.


        • Alex

          I'm confused. You're trying to compile C++ programs with Visual Basic? You should be using Visual C++.

          That aside, what error are you getting?

          • Tom

            Sorry - that was a typo - I'm using Visual Studio

            So these are the errors im getting:

            error C2062: type 'int' unexpected
            error C2143: syntax error: missing ';' before '{'
            error C2447: '{': missing function header (old-style formal list?)

            Alos, I wanted to mention, I chose an empty project, which doesn't force me to use the header in my project. Does that work as well, or is it recommended that I continue using and including that header file?

            • Alex

              Seem like normal error messages, you probably have a formatting error somewhere. Drop me an email via the site contact form and we can try to debug what's going on with your program.

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

  • Liang

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

Leave a Comment

Put all code inside code tags: [code]your code here[/code]