Page 1 of 1

Hello World: Your first C and C++ Programs Rate Topic: -----

#1 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1288
  • View blog
  • Posts: 7,575
  • Joined: 07-September 06

Posted 06 June 2015 - 08:47 PM

Learning C/C++ Series
Hello World: Your first C Program; your first C++ Program; and how they differ.

Now that you have gone through the steps of setting up your environment and getting everything running, it is time to get your feet wet! In this tutorial we will be creating a couple of very simple programs which will print out identical messages to the screen. However, they will also be using two different languages: One will be in C and the other will be in C++. This will help to start seeing some of the differences between the two languages and allow you to understand some of the similarities and differences (which will be covered in greater depths in later tutorials).

Why is this important to learn about?

HelloWorld programs are nice because they are generally some of the smallest running programs you can write for any given language that does something useful (useful here can be a little contrived, but it comes down to being able to print a message to the screen). They are good a highlighting differences between different languages' syntax without being overly complicated to the point of hindering understanding of the overall purpose.

Definitions of terms used.

directory -- A folder in the file system (like a folder in Windows).
Namespace -- A set of named symbols or variables.
int -- a 32-bit integer value (a whole number, there is no decimal portion).

Note: All examples were created using GCC (or G++), targeting the 98 standards. We'll do our best to point out anything that might not work in other versions.

Hello World: Your first C Program; your first C++ Program; and how they differ.

Starting off, go ahead and create a directory to work in. This is a good idea to do for all of your projects so you don't clutter your directories with unrelated programs. I went ahead and named my directory "HelloWorld", and this can be done by typing the following command into a Linux terminal (you should open one up now if you don't already have it. This can be done by opening your "activities" in Fedora and typing in "terminal" to find it quick, or clicking on the Ubuntu logo (in the top left corner) if you are using Ubuntu and doing the same (searching for "terminal"): mkdir HelloWorld

You should now have a new directory created. To list the directories in your current directory, type ls. You now want to move in to your HelloWorld directory by using cd HelloWorld. Open up a file named HelloWorld.c in your favorite editor (for the purposes of this tutorial I am using VIM, so I type the following into the terminal: vim HelloWorld.c), and type the following code in to it (I say type instead of copy and paste because you will start getting some muscle memory in place if you manually type it out, and if you want to go into programming you will be typing a lot of code, so you might as well start now):
#include <stdio.h>

int main(void)
{
	printf("Hello World!\n");
	return 0;
}



Now save the file.

What does this all do? You may be asking. Well, it does the following:

First we include the standard IO (input/ output) header file, which gives us access to functions like printf and scanf which can be used to write to and read from the terminal (respectively).

Second we have int main(void), this is a very important part. In every C or C++ program you write that can be executed from here on out, it will have a main function. This is the function that is called when you run your program. The int that shows up before main is the return type of the function; in this case we are saying that we will return a whole number. Why are we returning a whole number from the program? To let the user know if it succeeded or ran in to an error. In this case, returning 0 (as we do at the end of the function) means that there were no errors in the execution of the program. Any non-zero value is seen as an error code, meaning that the program ran in to a problem. The error code can be defined as you, the programmer, see fit. The (void) portion of the line is where we specify the parameters and their types for the function. In this case we don't take any paramters, and as such we say that there are none (void). We could also have just left the parenthesis empty like so: () to have said the same thing, but I like to be explicit in my programs (I believe it makes things easier to read and understand that way).

Third we have an opening curly-bracket ({). This matches up with the closing curly-bracket (}) to create a block. Blocks are nice because you can have zero or more statements within them, and they will be grouped (for lack of a better word) together. They also have some other special properties which we won't be covering in this tutorial. We put the body of the function between the curly-brackets.

Fourth, we have printf("Hello World!\n");. This is a statement, which calls the function printf with the string argument "Hello World!\n", and the semi-colon at the end says that the statement is over. In English, it basically says "print the string 'Hello World!' to the terminal window, and add a newline at the end.". Note that the double quotes here are what makes the argument a string. If we were instead to use single quotes, the compiler would expect a single character, instead of a series of characters. Also note that the \n is a special character which represents a newline. If you wanted the actual string "\n" to be printed out you would need to escape the back-slash with another back-slash: \\n.

Fifth we say return 0;, as I talked about above, this is returning a value back to the operating system (Linux) telling it that the program executed successfully. The operating system doesn't really act any differently based off of that knowledge, but there are ways for the user (you or I) to check the return status of programs we run and change what we do based off of that. If you are interested, you can type echo $? in your terminal to see the return status of the last program you ran.

Sixth we have the closing curly-bracket which tells the compiler that the main function is complete.

Sweet! We have a program, now how do we run it?

C and C++ require a step after writing the program called compiling. This makes the human-readable code that we wrote into an executable binary file that the operating system can read and run. To accomplish this with the HelloWorld.c file we just wrote, type the following command in to your terminal window (or a secondary terminal window if you want -- though make sure you are in the appropriate directory):
gcc -std=c11 -Wall -g -pedantic -o HelloWorldC HelloWorld.c

This will compile the program. gcc is the GNU C compiler, with the C 2011 standard (-std=c11), -Wall turns on extra warnings from the compiler (note that it doesn't turn on all warnings, just more of them). The -g compiles in additional debug information, which in a program as small as this doesn't help much, but later on it will be more useful, and the -pedantic removes all compiler-specific functionality from what the compiler will allow. This is nice because we don't have to worry about anything that is compiler specific (for instance if you were using the Bloodshed C/C++ compiler). The -o tells the compiler that we want to output a file and we want it to be called HelloWorldC which consists of the compiled instructions from HelloWorld.c.

If you do a ls in your directory, you should now see the HelloWorldC file there. You can run it by typing ./HelloWorldC in your terminal, and you should see the output:

Quote

Hello World!

printed to your screen.

Congratulations! You have now compiled and ran your first C program!

But this tutorial is also about looking at your first C++ program, so lets jump straight in to that.

In the same directory, open up a file called HelloWorld.cpp (here the cpp stands for C++, though cxx and cc are also common file extensions for C++ files), and type in the following:
#include <iostream>
using namespace std;

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



As you can see, it is more or less the same, but there are some striking differences. The first thing to notice is that the standard IO header file has been replaced by iostream, this is C++'s version of the IO header, which treats IO as a stream instead of a buffer. In the end they look the same, but they act differently, and use slightly different syntax.

The second thing that comes to view is this new and strange line using namespace std;. C++ added a new concept called namespaces which allow you to group functions, classes, structs, and types together in a namespace so you can have multiple things with the same name and not have conflicts. In this case the using is basically saying that the compiler should just assume we mean the std namespace, where std once again stands for standard. This allows us to not have to add std:: in front of cout and endl as we would have had to otherwise.
Finally, we have removed the printf line and replaced it with cout << "Hello World!" << endl;. This line says that we want to stream the string "Hello World!" followed by endl (which is a newline, or end of line[/il] to cout which is the standard C output (terminal).

Save this file off now and we will compile it. To do so we need to use a C++ compiler instead of a C compiler, but the command will look very similar: g++ -std=c++11 -Wall -g -pedantic HelloWorldCPP HelloWorld.cpp, as you can see all we changed was gcc got replaced with g++, which is GNU's C++ compiler.

If you run this program now (using ./HelloWorldCPP) you should see the same output as HelloWorldC had. Congratulations you have now written a program in C++ too!

Going Further

If you want to look at some other interesting things, try changing the programs so they output "Hello YOURNAME" instead.
For a little extra fun, try changing the return value to other numbers, compile and run the program, and see how echo $? changes.

In Conclusion

Now you know the basics of how to print messages to the terminal in C and C++, as well as the basic format of a function and how to compile your code.

See all the C/C++ Learning Series tutorials here!

Is This A Good Question/Topic? 2
  • +

Replies To: Hello World: Your first C and C++ Programs

#2 jimblumberg  Icon User is offline

  • member icon

Reputation: 4595
  • View blog
  • Posts: 14,504
  • Joined: 25-December 09

Posted 07 June 2015 - 04:07 PM

Quote

he (void) portion of the line is where we specify the parameters and their types for the function. In this case we don't take any paramters, and as such we say that there are none (void). We could also have just left the parenthesis empty like so: () to have said the same thing, but I like to be explicit in my programs (I believe it makes things easier to read and understand that way).


This is one of the many areas in which C and C++ differ. In C++ a function with an empty parameter list means that there are no parameters, as you stated above. But in C a function with an empty parameter list actually means that there can be any number of parameters, to guarantee no parameters will be passed you should use a void parameter. Also using a void parameter in C++ is considered a bad practice by many.

Quote

Note: All examples were created using GCC (or G++), targeting the 98 standards.

Look at your C compile line:

Quote

gcc -Wall -o HelloWorldC HelloWorld.c

Because you don't specify the standard to use (-std=c89) you can't be sure you're compiling to the C90 standard. The most recent version of gcc is now defaulting to -std=gnu11 instead of -std=gnu89. I recommend you implicitly specify the standard you wish to use along with enabling debugging support -g to enable proper debugging with gdb.

Your C++ compile line has the deficiency and you should specify the actual standard you wish to use, IE -std=c++11.

Jim
Was This Post Helpful? 0
  • +
  • -

#3 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1288
  • View blog
  • Posts: 7,575
  • Joined: 07-September 06

Posted 08 June 2015 - 08:40 AM

Quote

Because you don't specify the standard to use (-std=c89) you can't be sure you're compiling to the C90 standard. The most recent version of gcc is now defaulting to -std=gnu11 instead of -std=gnu89. I recommend you implicitly specify the standard you wish to use along with enabling debugging support -g to enable proper debugging with gdb.


Huh, alright. I wasn't aware that they had (finally) updated to use the (now 4-year old) standard as default. I'll update the tutorial accordingly tonight.
Was This Post Helpful? 0
  • +
  • -

#4 Xupicor  Icon User is offline

  • Nasal Demon
  • member icon

Reputation: 265
  • View blog
  • Posts: 637
  • Joined: 31-May 11

Posted 16 July 2015 - 09:37 PM

View PostBetaWar, on 07 June 2015 - 03:47 AM, said:

This line says that we want to stream the string "Hello World!" followed by endl (which is a newline, or end of line[/il] to cout which is the standard C output (terminal).


I would be wary teaching to use std::endl in place of \n. std::endl isn't just putting new-line character into the stream, it also flushes (calls std::flush) it. If you use that in a loop it can seriously harm performance of your program.

Another nitpic - instead of "standard C output" (terminal) - I'd just write "standard output stream" and show how standard output and standard input can be redirected in the console. Indeed, one can use standard input and standard output streams to read from and write to files.

BetaWar said:

Huh, alright. I wasn't aware that they had (finally) updated to use the (now 4-year old) standard as default.

That's beside the point. Remember about us, filthy Windows users! :) Depending on where we get our GCC from, it might be compiled with different defaults. ;)


Otherwise, nice job. Commendable. :)


Offtopic follows:
I'm actually in the process of writing a first episode of my own C++ tutorial (won't bother with C) and I have to say, writing a screenplay - because it's basically that, as I want to make it in a video form to share on youtube - isn't easy. Worse yet, while I like to pride myself in having quite good written English, my spoken English is atrocious. And when I was trying to record what I wrote... Oh god damn it, it's bad enough when I hear myself while speaking, but listening myself from a recording is so awkward and ... embarrasing. Even though nobody's around. :P Sigh.

Anyway, I can appreciate how hard it is to put together a piece of text, especially trying to teach something. Trying to find the balance between not overloading people with details, and yet providing them with knowledge...

This post has been edited by Xupicor: 16 July 2015 - 09:58 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1