Author Topic: Coding and Scripting > Learning C++  (Read 11879 times)

Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Coding and Scripting > Learning C++
« on: December 03, 2009, 12:46:38 PM »
C++ appears to have edged ahead in our poll, so lets get started.


Online gseaman

  • PCLinuxOS Tester
  • Hero Member
  • *******
  • Posts: 3795
Re: Coding and Scripting > Learning C++
« Reply #1 on: December 03, 2009, 06:24:55 PM »
Ok. You first! ;D

Galen

Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Re: Coding and Scripting > Learning C++
« Reply #2 on: December 04, 2009, 02:42:01 AM »
Okay then. The traditional first program --->

Code: [Select]
int  main  ()
{
   cout  << "Hello World!";
   return  0:
}

---> can be written on one line:

Code: [Select]
int  main  ()  {  cout  << "Hello World!";   return  0;  }
The semi-colon (;) separates statements in C++. This is how the entire code block can be written on one line; i.e. the statements are separated.

The reason for writing the separate statements on their own lines is to make the code more easily read by people. (Us.) Any given block of code is made up of statements. There could be only one or many. For simple programs, as in the above, it is not important to place each statement on a new line. However, when you begin to write larger projects, you will find that going back over your code to search for any errors or to find where you want to alter your code will become a much easier task with the statements on their own lines.


Offline Village Idiot

  • Hero Member
  • *****
  • Posts: 2345
  • Have A Nice Day.
Re: Coding and Scripting > Learning C++
« Reply #3 on: December 04, 2009, 03:26:10 AM »
Maybe I am really drunk, OK I am really drunk, but how do you make it all go.  ;)

 ;D
$ fortune
No Microsoft products were used in any way for the creation of this message.
If you are using a Microsoft product to view it, BEWARE! - I'm not
responsible for any harm you might encounter as a result.

Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Re: Coding and Scripting > Learning C++
« Reply #4 on: December 04, 2009, 03:47:36 AM »
Maybe I am really drunk, OK I am really drunk, but how do you make it all go.  ;)

 ;D


Get some coffee. ;) ;D The caffeine will awaken your brain. We've just started, so we haven't got there yet.

Meanwhile ---

Check out this list of online documentation and then review the Coding and Scripting topic and look for links to available docs.


Offline Village Idiot

  • Hero Member
  • *****
  • Posts: 2345
  • Have A Nice Day.
Re: Coding and Scripting > Learning C++
« Reply #5 on: December 04, 2009, 04:04:51 AM »
In your home directory...

In a file called hello.cpp type:
Code: [Select]
/*
 *  Simple HelloWorld with parameter and switch statement
 */

#include <iostream>
#include <cstdlib>   

using namespace std;

int main(int argc, char *argv[])
{
        int option = -1;
        if(argc > 1) // first arg is name of executable
                option = atoi(argv[1]); //  atoi - Converts string to long.

        switch(option)
        {
                case 1:
                        cout << "Hello World !" << endl;
                        break;
                case 2:
                        cout << "Bye World !" << endl;
                        break;
                default:
                        cerr << "Usage: " << argv[0] << " [1|2]" << endl;
        }
    return 0;
}

In a file called makefile type:
Code: [Select]
CC=g++
CFLAGS=-I.

hello: hello.o
$(CC) -o hello  hello.o $(CFLAGS)


At the command prompt type:
Code: [Select]
make

To run the program type:
Code: [Select]
./hello
or
Code: [Select]
./hello 1
or even
Code: [Select]
./hello 2

Good luck!

Note:
#include <cstdlib>  in hello.cpp

The cstdlib library is needed for the atoi function.  ;)

Source: http://www.socher.org/index.php/Main/HowToStartWithCppInLinux

Sorry to steal yer thunder Neal, but I couldn't help me-self!  :-[  ;D
$ fortune
No Microsoft products were used in any way for the creation of this message.
If you are using a Microsoft product to view it, BEWARE! - I'm not
responsible for any harm you might encounter as a result.

Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Re: Coding and Scripting > Learning C++
« Reply #6 on: December 04, 2009, 07:27:09 AM »
Thunder? What thunder? I'm trying to learn, too.


Online Old-Polack

  • Administrator
  • Super Villain
  • *****
  • Posts: 11589
  • ----IOFLU----
Re: Coding and Scripting > Learning C++
« Reply #7 on: December 04, 2009, 09:13:11 AM »
No offense, it's interesting, but copying a bunch of code to files, and and running "make" does nothing to teach one what each part of the code means, and why it's where it is, as to the order in which it's presented. To be able to write the code, one must know what each symbol, or charstring, means, as well as why it is structured in the manner it is, as one must know the meaning of each word, as well as proper structure, to be able to write a meaningful sentence, then combine sentences to make paragraphs.

This teaches the use of a makefile, which is good, but doesn't explain the meaning of the contents of said file. We know it works, without knowing how, or why, it works, so to make this meaningful, the next lesson should be a dissection of the code in hello.cpp, and the makefile. It is the how, and why, that will allow one to actually write one's own code.

For those that don't know;

charstring=character string; an arrangement of single typed characters into a unit, or string, as in a group of letters arranged to form a word.
Old-Polack

Of what use be there for joy, if not for the sharing thereof?



Lest we forget...

Offline The Chief

  • Hero Member
  • *****
  • Posts: 2253
Re: Coding and Scripting > Learning C++
« Reply #8 on: December 04, 2009, 11:52:07 AM »
Here's Neals program, as presented:

int  main  ()
{
   cout  << "Hello World!";
   return  0:
}

Here it is dissected and commented, line by line and element by element:

int - This defines the type of the return value of the function whose name follows.  In this case, and integer value (no fractions, usually a 32 bit, or 16 bit, or whatever is the native size for the architecture, binary value, with the high order bit reserved to indicate negative).

main - This is the name of the function. It can be anything, but "main" is special - it says to the computer, "Start here!"  It is the point where execution begins.

() - This is where any parameters (input values) to the function would be, in this case there are none, but you still need the space for them.

{ - This indicates the beginning of a block of code, in this case the "main" function.

cout - This is a call to a library function (console output)

<< - This is the redirection symbol (operator) telling the compiler to pass the next bit of data to the cout library function.

"Hello World!" - Sort of self explanatory.  Anything inside quotes (") is a literal string (just text).

; - This is the statement terminator - like the return key for the compiler.

return - This is one of the few actual C (or C++) keywords.  It tells the compiler to exit the current block of code and return to the caller (in this case, the command line) and optionally return any following value.

0 - This is the value to be returned.  There can be multiple return statements, and the value returned (which may ba a variable) is typically an indication of success (zero, usually) or failure (any other value, which may also indicate what the failure was).

: - This is, apparently a typo.  Should have been a ";" or statement terminator, indicating the end of the return statement.

} - This indicates the end of the code block, or, in this case, the program.

Note that brackets {} [] () must always be a matched pair.  

Also note that variables (temporary data storage) can have any name you desire - as long as it starts with an alpha character.  What it can store is determined by the statement that "declares" (creates) the variable, as in:  int returnvalue; or char stateflag;
Be aware that simply declaring a variable does NOT place any value into it - not even zero.  It mere assigns a memory location for it, and it will contain whatever happened to be in that memory location.  You should always initialize variables to some known value before first use.
« Last Edit: December 04, 2009, 11:53:59 AM by TheChief »

Retired Senior Chief, Retired Software Engineer, Active GrandPa

Offline Village Idiot

  • Hero Member
  • *****
  • Posts: 2345
  • Have A Nice Day.
Re: Coding and Scripting > Learning C++
« Reply #9 on: December 04, 2009, 12:43:13 PM »
No offense, it's interesting, but copying a bunch of code to files, and and running "make" does nothing to teach one what each part of the code means, and why it's where it is, as to the order in which it's presented. To be able to write the code, one must know what each symbol, or charstring, means, as well as why it is structured in the manner it is, as one must know the meaning of each word, as well as proper structure, to be able to write a meaningful sentence, then combine sentences to make paragraphs.

This teaches the use of a makefile, which is good, but doesn't explain the meaning of the contents of said file. We know it works, without knowing how, or why, it works, so to make this meaningful, the next lesson should be a dissection of the code in hello.cpp, and the makefile. It is the how, and why, that will allow one to actually write one's own code.

For those that don't know;

charstring=character string; an arrangement of single typed characters into a unit, or string, as in a group of letters arranged to form a word.

Yeah. That's a great point OP. An no, I'm not offended. I made the fatal mistake of failing to use comments.  :-[ Coming from a C background, I understood Neal's 'hello world', but couldn't off the top of my head 'make' it run as I could had it been written in straight C. So I yanked my "Teach Yourself C++ in 21 days" off the shelf (which I have never entirely read all the way through) and failed to find a simple hello.cpp / commandline string to do this simple task...  :(

So I googled, and still failed to find something that met the criteria, yet was simple in code, explanatory and also quick to compile.  :-\ I stumbled on the link I posted and offered it because it provided a fairly easy example that works on our systems.

I guess the point I was trying to 'make'  ;) was this is the way I learned to code (I was never taught): Find a working example no matter how obscure it is, and muck with the pieces that intrigue you and watch the results.

The other thing I liked about it was it demonstrated an example of receiving input and decision making. Far and away too many helloworld examples for all languages fail to offer this. And too many web tutes don't explain it early enough imo. I find it ironic because new programmers get interested in programing because chances are they have data which they wish to work on and modify.

Thanks to The Chief for the blow by blow "dissected and commented, line by line and element by element". Nice.  :)

Sorry all for sending the thread sideways.    :D
$ fortune
No Microsoft products were used in any way for the creation of this message.
If you are using a Microsoft product to view it, BEWARE! - I'm not
responsible for any harm you might encounter as a result.

Online Old-Polack

  • Administrator
  • Super Villain
  • *****
  • Posts: 11589
  • ----IOFLU----
Re: Coding and Scripting > Learning C++
« Reply #10 on: December 04, 2009, 01:41:29 PM »
F.Luent:

Nothing went sideways, it's an interesting piece, for all the reasons you mentioned. It just lacks the kind of dissection that's now been given for the more simple hello example. We now have a hello.cpp with a makefile combination, to dissect in a like manner to the way TheChief did the first one. There are new references introduced that weren't in the simpler code, so they too need to be defined for the new would be programmer. It's an opportunity, not a sideways move. :D
Old-Polack

Of what use be there for joy, if not for the sharing thereof?



Lest we forget...

Online Chomp

  • Full Member
  • ***
  • Posts: 173
Re: Coding and Scripting > Learning C++
« Reply #11 on: December 04, 2009, 02:39:32 PM »
You could also use

Code: [Select]
g++ hello.cpp
to compile and it will create an a.out executable or

Code: [Select]
g++ hello.cpp -o hello
if you want to create an executable named hello.  Easier than creating a makefile which can be intimidating if you just want to see your first code example run.

Offline Village Idiot

  • Hero Member
  • *****
  • Posts: 2345
  • Have A Nice Day.
Re: Coding and Scripting > Learning C++
« Reply #12 on: December 04, 2009, 02:49:40 PM »
Before:
Code: [Select]
int  main  ()
{
   cout  << "Hello World!";
   return  0:
}

Now:
Code: [Select]
int  main  ()
{
   cout  << "Hello World!";
   return  0;
}

I noticed the colon after 'return 0' should be a semicolon but still wont run as you suggest with g++

Quote
hello.cpp: In function ‘int main()’:
hello.cpp:3: error: ‘cout’ was not declared in this scope

What now?
$ fortune
No Microsoft products were used in any way for the creation of this message.
If you are using a Microsoft product to view it, BEWARE! - I'm not
responsible for any harm you might encounter as a result.

Online Chomp

  • Full Member
  • ***
  • Posts: 173
Re: Coding and Scripting > Learning C++
« Reply #13 on: December 04, 2009, 03:11:18 PM »
Neal's example won't compile because it doesn't include the iostream header file, which is what allows you to use the cout command.  Cout is an iostream function(an object) that accepts all data bound for standard output.  The iostream functions are a part of the standard C++ library.

Now, the definitions in iostream are "wrapped" in a namespace.  This is so that you can have a function with a similar name, but have it wrapped in a separate namespace, so that there is no conflict with another similarly named functions(hope that made sense).  You use the using command to tell the compiler that you will be using the declarations and/or definitions in the namespace.  All of the Standard C++ libraries are wrapped in a single namespace, which is std (for “standard”).

Code: [Select]
#include <iostream>

using namespace std;

int main ()
{
   cout  << "Hello World!"
   << endl;
}

Also notice I changed the return: 0 command to endl, which is another function provided by iostream.  This not only outputs the line "Hello World!", but also a new line when it's done.  Compile and run Neal's example(with the iostream header and namespace declared) and then mine to see the difference.

Edit: Also note that I didn't use ; at the end of cout  << "Hello World!".  This is because you only need to use ; at the end of every statement, not at the end of every line.  cout  << "Hello World!" << endl; is one statement, so I only need to use ; once to end it.
« Last Edit: December 04, 2009, 03:30:59 PM by Chomp »

Offline Neal ManBear

  • Administrator
  • Super Villain
  • *****
  • Posts: 15847
  • LXDE! Coffee, Bacon and Cheesecake!
Re: Coding and Scripting > Learning C++
« Reply #14 on: December 04, 2009, 03:13:43 PM »
It may seem a bit picky, but my post that F.Luent complained of not providing something to "make it go" was not about the code or compiling the code. Please re-read it. You'll see that it was about line structure.

As I said when I was nominated to teach:
Quote
"Teacher?" Me? Are you out of your ever-loving minds? I don't know enough to teach, though I do appreciate the honour. If I tried to teach the subject, we'd all be in trouble. ::)

That was my attempt to start teaching. It appears to have failed horribly on the start up. Like my previous attempt to start a discussion on the symbols (I started off with { and } and said that what is between is a block of code.), it was something that interested me.  

TheChief,
If you would do the teaching, I'd be grateful.