C++ Programming/Examples/Hello world - Wikibooks, open books for an open world (2024)

Contents

  • 1 Hello World - Writing, Compiling and Running a C++ Program
    • 1.1 Troubleshooting
  • 2 Your First C++ Program Explained
    • 2.1 The preprocessing directive
    • 2.2 main Function
    • 2.3 Printing Hello World!
  • 3 Modifications to the Above Program
    • 3.1 Comments
    • 3.2 Flushing the Output Stream Buffer
    • 3.3 Returning Success Code
    • 3.4 Whitespace and Indentation

Hello World - Writing, Compiling and Running a C++ Program[edit | edit source]

Below is an example of a simple C++ program:

// 'Hello World!' program  #include <iostream> int main(){ std::cout << "Hello World!" << std::endl; return 0;}


When you write a program, you use a development environment. Your development environment can be a basic text editor or a feature rich C++ integrated development environment (IDE). You should not use a word processor like Microsoft Word, because it adds formatting codes to the text.

If a compiler is not already available to you, see the Where to get a compiler Section of the book.

Open your development environment and type the program shown (or copy and paste it) and save it as hello.cc.

Now compile it using the C++ compiler:

COMMAND_PROMPT> g++ hello.cc -o hello

The example uses GCC, the GNU Compiler Collection ( http://gcc.gnu.org ) but you could use any other compiler, or use an IDE to compile it. The above command would produce an executable called hello or hello.exe. Invoke the executable to run your first C++ program:

Unix:

COMMAND_PROMPT> ./helloHello World!COMMAND_PROMPT>

Microsoft Windows:

COMMAND_PROMPT> dear helloHello World!COMMAND_PROMPT>

Text that is italicized is typed by you and the bold text is output by the program. If you use an IDE, it might automatically color the code for you based on the syntax.

Troubleshooting[edit | edit source]

g++
command not found

You don't have the GNU C++ compiler installed. If you have a different compiler, check its documentation for the correct compilation command.

Note:
There is detailed information on how to get a compiler and how to install it on the Where to get a compiler Section.
In Appendix B:External References you will also find references to other freely available compilers and even full IDEs you can use.

Wrong Compiler Command

Lot of weird errors, mentioning many times:

undefined reference to `std::basic_ostream' [..]

Usually ending with:

collect2: ld returned 1 exit status

To use g++ to compile your hello.cc, use:

g++ hello.cc -o hello

For gcc, use:

gcc hello.cc -o hello -lstdc++

Note:
For simplicity, we assume that the file is in the path you are using...

hello
command not found

You did not type the full path, try:

./hello

Is there a hello program in this directory? Can you see it when you type ls? If not, your compilation (g++ hello.cc -o hello) failed or you have changed to a wrong directory.

If you do not specify -o hello, g++ names the output file a.out (assembler output) for historical reasons. In such a case, type:

./a.out

to execute the program.

Your First C++ Program Explained[edit | edit source]

The preprocessing directive[edit | edit source]

Some features of C++ are part of the language and some others are part of a standard library. The standard library is a body of code that is available with every C++ compiler that is standards compliant. When the C++ compiler compiles your program it usually also links it with the standard C++ library.

When you use features from the library, C++ requires you to declare the features you will be using. The first line in the program is a preprocessing directive. In our example it is shown bold and italicized:

The preprocessing Directive for IOStreams
 #include <iostream>

This line causes the C++ declarations which are in the iostream header to be included for use in your program. Usually the compiler inserts the contents of a header file called iostream into the program. Where it puts it depends on the system. The location of such files may be described in your compiler's documentation. A list of standard C++ header files is in the standard headers reference tables.

The iostream header contains various declarations for input/output (I/O). It uses an abstraction of I/O mechanisms called streams. For example there is an output stream object called std::cout which is used to output text to the standard output. Usually, this displays the text on the computer screen.

The preprocessor is a part of the compiler which does some transformations to your code before the actual compiler sees it. For example, on encountering a #include <iostream> directive, it replaces the directive with the contents of the iostream header file.

main Function[edit | edit source]

int main(){ // ...}

The lines above represent a block of C++ code, given the name main. Such a named block of code is called a function in C++ parlance. The contents of the block are called the body of the function.

The word int is shown in bold because it is a keyword. C++ keywords have some special meaning and are also reserved words, i.e., cannot be used for any purpose other than what they are meant for. On the other hand main is not a keyword and you can use it in many places where a keyword cannot be used (though that is not recommended, as confusion could result).

Every (standards-compliant) C++ program must define a function called main. This is where the execution of the program begins. As we shall see later, main may call other functions which may call yet other functions. The compiler arranges for main function to be called when the program begins executing. (Although this is generally true, it is not always true. There is an exception to main's being executed at the very beginning that we will see later.)

Now let us look at the code inside the main function.

Printing Hello World![edit | edit source]

The first line in main uses the std::cout object to print the string (sequence of characters) Hello World! and end the line:

std::cout << "Hello World!\n";

This line is a C++ statement. C++ statements are terminated by a semicolon (;). Within the statement <<, called the insertion operator is used to output the string using the std::cout stream. C++ strings are enclosed within double quotes ("). The quotes themselves are not part of the string and hence not printed. The sequence \n is used within a string to indicate the end of the current line. Though the sequence is represented by two characters, it takes up only one character's worth of memory space. Hence the sequence \n is called the newline character. The actual procedure to start a new line is system-dependent but that is handled by the C++ standard library transparent to you.

Note:
C Programmers should not confuse the insertion operator with the bitwise shift operator in C. C++ has a feature called operator overloading which allows the two interpretations of << to coexist. In C++, I/O is the primary use of << and >>, and bit shifting is a relatively uncommon use.

Modifications to the Above Program[edit | edit source]

Here is the same program with minor modifications:

// This program just displays a string and exits#include <iostream> int main(){ std::cout << "Hello World!"; std::cout << std::endl; return 0;}

Comments[edit | edit source]

The line added at the beginning:

// This program just displays a string and exits

is a comment that tries to explain what the code does. Comments are essential to any non-trivial program so a person who is reading the code can understand what it is expected to do. There is no restriction to what is contained between the comment delimiters. The compiler just ignores all that is there in the comment. Comments are shown italicized in our examples. C++ supports two forms of comments:

  • Single line comments start with a // and extend up to the end of the line. These can also be used to the right of statements to explain what that statement does.
  • Multi-line comments start with a /* sequence and end with a */ sequence. These can be used for comments spanning multiple lines. These are also known as C-style comments as this was the only type of comment originally available in C. e.g.:
/* This program displays a string and then it exits */

Comments are also used at times to enclose code that we temporarily want the compiler to ignore, but intend to use later. This is useful in debugging, the process of finding out bugs, or errors in the program. If a program does not give the intended result, by "commenting out" code, it might be possible to track which particular statement has a bug. As C-style comments can stop before the end of the line, these can be used to "comment out" a small portion of code within a line in the program.

Flushing the Output Stream Buffer[edit | edit source]

Whenever you write (i.e., send any output) to an output stream, it does not immediately get written. It is first stored in memory and may actually get written any time in the future. This process is called buffering and the regions in memory used for storing temporary data like this are called buffers. It is at times desirable to flush the output stream buffers to ensure all data has been written. This is achieved by applying the insertion operator to an output stream and the object std::endl. This is what is done by the line:

std::cout << std::endl;

Before flushing the buffer, std:endl also writes a newline character (which explains its name, end line). Hence the newline is omitted in the string printed in the previous line.

Returning Success Code[edit | edit source]

In most operating systems, every program is allowed to communicate to the invoker whether it finished execution successfully using a value called the exit status. As a convention, an exit status of 0 stands for success and any other value indicates failure. Different values for the exit status could be used to indicate different types of failures. In our simple program, we would like to exit with status 0.

C++ allows the main function to return an integer value, which is passed to the operating system as the exit status of the program. The statement:

return 0;

makes main to return the value 0. Since the main function is required to return an integer, the keyword int is used to begin the function definition. This statement is optional since the compiler automatically generates code to return 0 for the main function for the cases where control falls off without a return statement. This is why the first program worked without any return statements. Note that this is only a special case that applies only to the main function. For other functions you must return a value if they are declared to return anything.

Common Programming Error 1Though the return statement is optional, main should not be declared to return void (a function declared as void is a function which does not return anything) as in some other languages like Java. Some C++ compilers may not complain about this, but it is wrong. Doing this could be equivalent to returning just about any random number that happened to be stored in a particular memory location or register, depending on the platform. This practice can also be potentially damaging to some operating systems, which rely on the return code to determine how to handle a crash or other abnormal exit.

Whitespace and Indentation[edit | edit source]

Spaces, tabs and newlines (line breaks) are usually called whitespace. These are ignored by the compiler except within quotes, apart from the rule that preprocessing directives and C++-style comments end at a newline. So the above program could as well be written as follows:

// This program just displays a string and exits, variation 1#include <iostream>int main() { std::cout<<"Hello World!"; std::cout<<std::endl; return 0; }

Note, however, that spaces are required to separate adjacent words and numbers.To make the program more readable, whitespace must be used appropriately.

The conventions followed when using whitespace to improve the readability of code constitute an Indent style. For example, with alternate indent styles, the program could be written like this:

// This program just displays a string and exits, variation 2#include <iostream> int main() { std::cout << "Hello World!"; std::cout << std::endl; return 0;}

or like this:

// This program just displays a string and exits#include <iostream> int main(){ std::cout << "Hello World!"; std::cout << std::endl; return 0;}
C++ Programming/Examples/Hello world - Wikibooks, open books for an open world (2024)

FAQs

How do I write Hello World in C++? ›

How To Make a Computer Say Hello
  1. #include <iostream>
  2. int main() {
  3. std::cout << "Hello World! Welcome to your first C++ program!" << std::endl; }
Sep 20, 2021

What is the correct syntax to output Hello World in C++? ›

std::cout << "Hello world!";

The text within the quotation marks is printed by std::cout. It has to be preceded by and then the format string. The format string in our example is "Hello World!"

How to print Hello World N times in C++? ›

Here's an example:
  • #include <iostream>
  • int main() {
  • for (int i = 0; i < 100; i++) {
  • std::cout << "Hello world\n";
  • }
  • return 0;
  • }
Jan 3, 2023

How to run C++ code? ›

Run your code in a command window
  1. To open a command prompt window, press Windows+R to open the Run dialog. Enter cmd.exe in the Open textbox, then choose OK to run a command prompt window.
  2. In the command prompt window, right-click to paste the path to your app into the command prompt. Press Enter to run your app.
Mar 20, 2024

Where to write C++ code? ›

An IDE (Integrated Development Environment) is used to edit AND compile the code. Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can be used to both edit and debug C++ code.

Is C++ too hard for beginners? ›

C++ is somewhat difficult to learn, especially if you have never programmed before or you have never used a low-level programming language before. If you are a beginner with no programming experience, you should expect it to take at least three months to learn the basics.

Which C++ is best for beginners? ›

If so, Codio's edX course, C++ Programming: Basic Skills, is the perfect fit for you. It's designed for complete beginners to coding, with no prior programming experience required. By the end of the course, you'll have a solid foundation in computer science and programming.

What is C++ in simple words? ›

C++ (or “C-plus-plus”) is a generic programming language for building software. It's an object-oriented language. In other words, it emphasizes using data fields with unique attributes (a.k.a. objects) rather than logic or functions. A common example of an object is a user account on a website.

Is C++ hard to learn? ›

C++ is hard to learn because of its multi-paradigm nature and more advanced syntax. While it's known to be especially difficult for beginners to learn, it's also difficult for programmers with no experience with low-level languages.

What is C++ programming with an example? ›

C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for creating large-scale applications. C++ is a superset of the C language. A related programming language, Java, is based on C++ but optimized for the distribution of program objects in a network such as the internet.

How many keywords are in C++? ›

C++ Keywords: There are 32 keyword in C and 31 new keywords are added in C++, so 63 keywords in C++. Keywords are special words whose meaning has all ready been known to the compiler. All keywords should write in small letters and cannot be used as a identifier or variable names.

How to code Hello World? ›

Basic example: Creating and running “Hello World”
  1. Create the following C program and name the source file hello.c : #include <stdio.h> int main(void) { printf("Hello World!\n"); return 0; }
  2. Compile the program: ...
  3. Run the program by entering the following command: ./hello.

How to write a sentence in C++? ›

Example 1
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main() {
  5. string my_str;
  6. cout << "Enter a pet name: ";
  7. getline(cin, my_str);
  8. cout << "My pet's name is " + my_str + "!";

How to set up VS code for C++? ›

To successfully complete this tutorial, you must do the following:
  1. Install Visual Studio Code.
  2. Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for 'c++' in the Extensions view (Ctrl+Shift+X).
  3. Install the Microsoft Visual C++ (MSVC) compiler toolset.

How to say Hello World in C code? ›

printf("Hello World \n"); printf("hey! welcome you all"); In the above code, we have mentioned \n in the printf() to display the output in the new line.

How to print Hello World in C++ using class? ›

class HelloWorld { public: void PrintHelloWorld() { std::cout << "Hello World! \n"; } }; In this Hello World C++ code example, we have created a class “HelloWorld” with one public function PrintHelloWorld(). Public function means that other functions outside this class may call it directly.

What is the command for Hello World? ›

printf("Hello World"); This line tells the compiler to display the message “Hello World” on the screen. This line is called a statement in C.

References

Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 6070

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.