.. _lecture3: Introduction to C++ ################### .. include:: /header.inc .. seealso:: Text: Chapter 2 Obviously, when you develop programs in C++, you will spend most of your time writing `statements` that manipulate your data. We need to review the basic statements of this language, and see how they are different from those you learned in your previous language. We will use "syntax diagrams" to show you how things are put together. .. note:: These diagrams are a common way to explain how you are to build programs. Following these diagrams will result in no syntax errors in your code! Trust me, the compiler will tell you if you write them wrong. These diagrams (and EBNF rules) say nothing about style. We will spend some time on style in a later lecture. For now, we will concentrate on learning on how the statements are formed. Variable Declarations ********************* C++ is very different from a language like Python in that all variables you use must be ``declared`` first. That ``declaration`` will tell the compiler what type of data this variable will hold, and possibly what initial value to put in that variable before the program runs. There are a lot of data types we can use in our program, and learning these types is part of your job as a developer. For now, we will just use the simple, basic, types: * ``int`` - signed integers * ``float`` - floating point numbers * ``char`` - single characters * ``bool`` = boolean (either ``true`` or ``false``) There are lots of other types, and we will explore them later. Here is how we "declare" a variable: .. image:: images/declaration.png :align: center We will start off with simple data types: .. image:: images/type_specifier.png :align: center That "expression" is just any mathematical expression that reduces to the kind of data type specified for this identifier. Formally, the identifier names a ``variable`` in your program, which can only hold data of the specified type. This is definitely not like Python, where a variable can hold anything you like and you can change it as you wish. Once a variable is declared, its type is fixed for the life of that variable! Basic structures **************** All modern programming languages are based on the three basic programming structures: The sequence ============ .. image:: images/Sequence.png :align: center This structure is obvious. We perform one thing after another! The decision ============ .. image:: images/Decision.png :align: center This structure forms the basic of making decisions in our programs. We form expressions that produce `logical` results. Those results have only `true` or `false` values` and will cause us to branch in one of only two possible ways in our programs. We can combine several sets of these to perform more complex questions, but they all boil down to basic two state questions. The loop ======== .. image:: images/WhileDo.png :align: center This loop asks a question that decides whether to do a task or not. If we do the task, we go back and ask the question again. The minimum number of times we do the task is zero in this form of loop. Obviously, we could set up other forms of loops, but this one is probably the most general. There are other forms of statements, added to our arsenal of programming tools just to make our lives as programmers more simple. They are not really essential. In the material that follows, I will show you syntax diagrams for the most common forms of C++ statements you will be using in this class. These are by no means the only C++ statements you will learn, just a set to get you started. You should start here, then study these and see if they map into Python, or other languages you might have seen before. Introductory C++ Statements *************************** Let's see the most common statements you will need to learn: Input/Output Statements ======================= At the top of any file where you want to generate output, or read something from the keyboard, place this line: .. code-block:: c++ #include The "include" tells the compiler to read the named file as though you typed it in at this spot. The file we are including here is called a header file, but you can include any kind of file you like, even another code file. This is legal, but there is no good reason to do that. We will restrict what we "include" in this class. The angle brackets around ``iostream`` tells the compiler that this file can be found with system files that come with the compiler. It knows where to look for this file. .. note:: If you are including a file that you wrote, you will surround that file name with double quotes! Console Output -------------- In order to have your program write output to the console, you use the special variable called ``cout`` (console output) and send strings or variable names into that ``cout`` gadget. We will need to use a weird notation that looks like this: .. code-block:: c++ #include ... std::cout << "Hello, World! << std::endl; the "std::" notation tells the compiler that ``cout`` is in something called a ``namespace``. Specifically, it is in the ``std`` namespace. We will explore the ``namespace`` idea later. For now, just use the example shown above. Here is another output example: .. code-block:: c++ std::cout << "The current value in variable test is " << test << std::end; Here we generated a string, then told the compiler to print out whatever is stored in the ``test`` variable at this point in your program C++ will use the declared data type for that variable to figure out how to display the current value stored there. The "<<" can be thought of as "sliding" something toward the left where you can imagine the console lives. You can add more "<<" on one line, and those things slide to the left and are output on the end of anything printed before. You "compose" your output as you like. The ``std::endl`` send a "newline" to the console, ending the current output line, and setting you up so the next things you output will fall on the line below this one. Console input ------------- The special name we use for input is ``std::cin`` (console input). In this case, we again imagine the console as living to the left of our screen, and when we type something, it will slide from the left into a storage container of some sort. It looks like this: .. code-block:: c++ int test; ... std::cin >> test; Here, I set up (declared) an integer variable named "test". On the input line, I told the compiler to stop the program, and wait for the user to type in a number. The program will try to convert the stuff typed into an integer, and store the result in the "text" container. If the user types weird stuff when you wanted an integer, you program may break. We will learn how to deal with this later. .. note:: If you expect the user to enter something, it is always a good idea to output something telling them what to do. There is nothing worse than writing a program that stops and waits for the user to enter something, and says nothing on the screen. To the user, it looks like the program is broken! Chaining Input -------------- It is legal to do this (but I never do it): .. code-block:: c++ int a,b; ... cin >> a >> b; Notice that I declared two integers on the same line. I also asked for input into both variables on the same line. The first number typed is stored in "a", and the second number types ends up on "b". C++ tries to figure out what the user entered, and will read everything up to a character that does not make sense for the kind of item it expects. That means the user could type "123abc", and the system would stop looking for a number when it sees that "a". The problem with this is that if your program asks for another number, the input from the keyboard has an unprocessed sequence of characters waiting, and those letters are not legal for an integer. You are going to have problems with this. Again, there are ways to deal with this, and we will explore those later. That is enough to let you write some simple code that uses both input and output (which you need to do for this week's lab project). Assignment Statement ==================== Now, we need to look at how you do some number crunching and save the results in a variable: .. image:: images/Assignment.png :align: center The ``identifier`` shown here names a variable in your program. That name must have been declared earlier in your code. You should pick a name that helps you understand what that variable is all about. ``max_count`` is much better than ``x24``! If Statement ============ Our basic decision statement looks like this: .. image:: images/if_statement.png :align: center That ``condition`` is a ``logical expression`` where we ask a question about our data. The expression should evaluate to either a "true" or a "false". You will typically form a logical expression using a ``relational operator``. These should look familiar: * ``>`` - greater than * ``>=`` - greater than or equal * ``<`` - less than * ``<=`` - less than or equal * ``!=`` - not equal * ``==`` - is equal to Logical expressions always evaluate to a boolean value of ``true`` or ``false`` (note the case) in C++. You can also use the ``not`` operator, which is the exclamation point. * ``!(a >= b)`` - means ``a`` is less than ``b``, right? (What is the opposite of greater than or equal?) While Statement =============== Here is our most basic loop: .. image:: images/while_statement.png :align: center Notice we use another ``condition`` here. This one controls whether we loop or not. If you manage to get into the loop, you must alter something in the loop body to make the condition fail, or you will loop "forever" (or until you kill the program!) Do-While Statement ================== Here is another common loop in C++: .. image:: images/do_statement.png :align: center This loop executes the "statement" at least once. I hardly ever use this one, but it is available if needed. For Statement ============= The "for loop" is by far the most used loop in programming. It really is used when you know exactly how many times you want to loop. .. image:: images/for_statement.png :align: center There are three parts to this statement, separated by semicolons. The first part is run before the loop begins. We declare a variable here to be used to control the loop. We give that variable an initial value. The second clause is processed to determining if we are to loop. It this expression evaluates to "false" the loop stops. If it is true, we will run the statement inside the loop. The third clause is processed after the loop body. It is most often used to modify the loop variable. Here is a simple example: .. code-block:: c++ for (int i=0; i<10; i++) { std::cout "The loop counter value is " << i << std::endl; } .. note:: Those curly brackets are not really needed here, since I only want one statement for the loop body. It is not wrong, just unneeded. This statement is pretty different from Python's "for loop". There is no funny "range" to worry about here. I actually like this form better than what we need in python! Compound Statement ================== In all of the diagrams shown above, you are allowed only one "statement" inside of the statement you are defining. For example, in that "if" statement, after the condition (in parentheses in C++) you can only have one statement. If you have an "else" you can only have one statement there as well. That will not do. C++ solves this problem by providing a "compound statement" that is basically a list of statements surrounded by curly brackets: .. image:: images/compound_statement.png :align: center Now, the style rules say you should indent the list of statements placed inside of the braces. C++ really does not care, but readers of you code absolutely do care. The conventional wisdom today says you should indent four spaces. But how you style those curly braces differs with the project or programmer. In my style, I place the open curly bracket at the end of the first line. Like this: .. code-block:: c++ if (value >= 0) { std::cout << "we have a positive value" << std::endl; std::cout << "Isn't that nice?" << std::end; } Notice that I line up the close curly bracket with the "if". There is another style in common use, but I do not like it since is wastes spece in my code. It looks like this: .. code-block:: c++ if (value >= 0) { std::cout << "we have a positive value" << std::endl; std::cout << "Isn't that nice?" << std::end; } In this style the curly braces line up. I just do not like that mostly empty line at the top. Whatever style you pick, be consistent. If you have an "else" clause, here are the two styles you might use: .. code-block:: c++ if (value >= 0) { std::cout << "we have a positive value" << std::endl; std::cout << "Isn't that nice?" << std::end; } else { std::cout << "we have a negative value (or is it zero?" << std::endl; std::cout << "I suppose that is OK" << std::endl; } Or, you might write it as this: .. code-block:: c++ if (value >= 0) { std::cout << "we have a positive value" << std::endl; std::cout << "Isn't that nice?" << std::end; } else { std::cout << "we have a negative value (or is it zero?" << std::endl; std::cout << "I suppose that is OK" << std::endl; } Again, you get t pick, but be consistent. The compiler could care less. You could write the entire thing on one extremely line and it would compile just fine. .. note:: Guido thought all of this was just plain silly. (He wrote Python using C++!) You ought to indent code properly anyway, Guido he designed Python so that you had to indent properly, and then he got rid of those ugly brackets. When I first started writing Python, I hated that indent stuff, but then it dawned on me that I did indent properly, and I hardly ever used the curly brackets again! (well, until I discovered Python dictionaries!) Other Statements **************** Obviously, this set of statements is not complete, but this is enough to get you started. Your book has examples that will get you figure out all of this. Use the example code in the book to fill in the missing details. In the next section, we will look at how you should structure a project. Writing your Code ***************** You will be writing a number of C++ programs in this class. So, let's start off with a good foundation. Here is a template you should use as a start on every program you write. The template is not a single file, it is a directory structure with a number of things I will require that you include in each project you submit for grading! Setting up a new project ************************ As part of my effort to improve your programming professionalism, I am going to require a defined directory structure for all work you submit for grading. or our first C++ program example, we will keep tings simple. All code will live in a single directory, with a suitable name. Program Starting Point ********************** The sample program in this template will get you started, but it is not what I expect to see in your actual code. Every file you create should include a header at the top indicating who wrote the file, when, and why, and anything else that will make it easier for someone else to figure out why they are even reading this code. Here is a better starting point: .. code-block:: c // hello.cpp - basic hello, world test program // // Author: Roie R. Black // Date: Sept 2, 2018 // Course: COSC1337 // // to compile, try this: // g++ hello.cpp -o hello.exe (leave off the .exe on Mac/Linux) // include int main(int argc, char * argv[]) { cout << "Hello, World!" << endl; return 0; } .. warning:: That header very definitely should be changed on your submissions. If It looks like I wrote it, any grades will be given to me, not you! Obviously, as we write programs with more than one file, the header at the top of each file should be different. The primary routines in each file should be mentioned in the header, as should basic information on how to use those routines. EBNF Start Rule *************** Since I showed you the EBNF notation, let's include a rule for your main routine in any C++ program: .. rail:: program : includes functionHeader functionBody ; .. rail:: functionHeader : "int" "main" parameterList ";" ; .. rail:: parameterList : "(" mainParameters ")" ; .. rail:: functionBody : lbrace ( statement + ) rbrace ; These rules, while formally correct, do not say anything about style, and style is something you must learn how to use. Failure to consider style is a serious offense in the programming world, in spite of the fact that the language does not care (except for Python, of course). Use good style! What are all of these things? Includes ======== Includes are those lines that provide access to routines defined elsewhere. In our normal template we include this line:: #include The sharp character at the front of this line actually marks this line as a `directive` to something called the C++ Preprocessor, a tool that reads your file and prepares it for actual compiling. In this case, the contents of a file named `iostream` are located and copied into your file before your file is handed to the compiler. The angle brackets around the file name tell the preprocessor that this file is located where the compiler, itself, is located on your system. It is a system file. User files we want to include will be named with quotes, inside of which we will tell the system where the file is located. Function Header =============== The `function header` defines something called a `signature` for this function. In C++ a signature for a function includes the return type (if any) of the function (`int` in this case, the name of the function (`main`) and the number and type of any arguments the function requires). Our `main` function has an integer return type, the name `main`, and exactly two arguments, the first an integer, and the second, well, it is a pointer to an array of strings. Don't worry about that for now, we will get to it. Function Arguments ================== A function can have zero of more arguments (or parameters, as they are also called). The open and close parentheses are required in any case. The `arguments` in this case is a comma-separated list of two items: .. rail:: mainParameters : "int" "argc" "," "char" "*" "argv[]" ; The actual names `argc` and `argc` can be anything you like, but folks will look at you funny if you change them. Function Body ============= The function body is where all the action is. Those parameters have names, and those names are available inside the body. We can include as many statements as we like. The body is actually a rule you will see elsewhere in the language. A block of statements surrounded by curly braces is what is required here. That same block of statements will appear twice in an `if-then-else` statement as we will see later. The very last of the statements in the `main` function body should be this:: return 0; Which hands back the value zero to the operating system which is what will actually launch your program. Windows could care less about this value, but other operating systems pay attention to this. Scripts that launch a number of programs in a row will use the return code to decide if to continue or not. Any return value other than zero is considered a failure, and that will stop further processing in a script. This line is often left off, with no problems, but it is still good to include it. The statement list in the body of your `main` function can be very complex, but that makes figuring out what you are doing just plain hard. I recommend that you use other procedures/functions to break up your code into logical parts with good names, so the reader can see the basic organization of your program easily. Here is something you might see: .. code-block:: c int main(int argc, char * argv[]) { get_input_data(); process_data() output_final_results() return 0; } I have no problem with asking a program to identify itself, especially if it is a console program. Just replace "Hello, World" with something more meaningful! Will this code compile? Try it and see: .. code-block:: bash $ g++ hellp.cpp -o hello In this line ``g++`` is the name of the program we want to launch. This program is actually a manager for C++ tools you never see. In this case, we are handing the C++ source file to this program. ``g++`` is smart enough to realize that we want to compile that file. The ``-o hello`` tells the program that it should name the final program ``hello``. .. warning:: On a PC the proper name would be ``hello.exe``. On Linux/Mac, there is no extension on an executable program file, Windows always expects ``.exe`` (or one of a few other extensions we will not worry about here). You are now ready to write your first real C++ program. It is pretty simple!