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

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

What is C++ programming with an example? ›

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.

How to compile C++ code? ›

Compile and Execute C++ Program
  1. Open a text editor and add the code as above.
  2. Save the file as: hello.cpp.
  3. Open a command prompt and go to the directory where you saved the file.
  4. Type 'g++ hello. cpp' and press enter to compile your code. ...
  5. Now, type 'a. ...
  6. You will be able to see ' Hello World ' printed on the window.

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

One of the best C++ courses for beginners which is a complete package to dive deep into the beginner to advanced level concepts is Master C++ Programming – Complete Beginner to Advanced offered by GeeksforGeeks. This course is taught by Mr.

How should I practice C++ for beginners? ›

C++ Basic Exercises
  1. Write a program in C++ to find Size of fundamental data types. ...
  2. Write a program in C++ to print the sum of two numbers using variables. ...
  3. Write a program in C++ to check the upper and lower limits of integer. ...
  4. Write a program in C++ to check whether the primitive values crossing the limits or not.

How to program 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 an introduction in C++? ›

C++ is one of the world's most popular programming languages. C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems. C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs.

What is the basic syntax of C++? ›

The basic syntax of C++ is very simple. A statement is a unit of code terminated by a semicolon. Statements are used for a variety of purposes to call functions, declare and initialize variables, or to operate on expressions. A function is a larger unit of code that may contain many statements.

What is the first line of the code in C++? ›

Syntax of C++ In the very first line, #include signifies the header file. This header file is a library of C++ that helps the programmer with standard input-output objects. In the next line, there is using namespace std; statement.

What should be my first C++ project? ›

List of Projects
  • Banking system.
  • Tic Tac Toe game.
  • Login and registration system.
  • Casino game.
  • Hotel management system.
  • Student report.
  • Snake and ladder game.
  • Sudoku game.
Feb 26, 2023

How to start writing code in C++? ›

C++ Get Started

To start using C++, you need two things: A text editor, like Notepad, to write C++ code. A compiler, like GCC, to translate the C++ code into a language that the computer will understand.

How to run Hello World in C++ in VS Code? ›

Make sure you have a C++ compiler installed before attempting to run and debug helloworld.cpp in VS Code.
  1. Open helloworld.cpp so that it is the active file.
  2. Press the play button in the top right corner of the editor.
  3. Choose g++ build and debug active file from the list of detected compilers on your system.

How do you write Hello World in Notepad ++? ›

Type std::cout << "Hello World!"; into Notepad++ and press ↵ Enter .

Top Articles
Autry Morlan Chevrolet Vehicles
Claves para entender cómo funciona y qué es el pase sanitario
Craigslist Monterrey Ca
Dee Dee Blanchard Crime Scene Photos
Sissy Hypno Gif
Fusion
Sprague Brook Park Camping Reservations
Minn Kota Paws
Best Fare Finder Avanti
065106619
Craiglist Kpr
Brett Cooper Wikifeet
Clear Fork Progress Book
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Farmer's Almanac 2 Month Free Forecast
Bank Of America Financial Center Irvington Photos
Sadie Proposal Ideas
Army Oubs
Mikayla Campinos Laek: The Rising Star Of Social Media
Foxy Brown 2025
Tips on How to Make Dutch Friends & Cultural Norms
Qual o significado log out?
Tips and Walkthrough: Candy Crush Level 9795
Rapv Springfield Ma
Craiglist.nj
Best Middle Schools In Queens Ny
Pioneer Library Overdrive
Infinite Campus Asd20
Mami No 1 Ott
031515 828
Prévisions météo Paris à 15 jours - 1er site météo pour l'île-de-France
Kempsville Recreation Center Pool Schedule
The Ultimate Guide to Obtaining Bark in Conan Exiles: Tips and Tricks for the Best Results
Siskiyou Co Craigslist
Salons Open Near Me Today
Wcostream Attack On Titan
Bee And Willow Bar Cart
Navigating change - the workplace of tomorrow - key takeaways
SOC 100 ONL Syllabus
National Insider Threat Awareness Month - 2024 DCSA Conference For Insider Threat Virtual Registration Still Available
Hellgirl000
Check From Po Box 1111 Charlotte Nc 28201
Tedit Calamity
Disassemble Malm Bed Frame
Jamesbonchai
Nami Op.gg
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Here's Everything You Need to Know About Baby Ariel
Blue Beetle Showtimes Near Regal Evergreen Parkway & Rpx
Reli Stocktwits
Streameast Io Soccer
Sapphire Pine Grove
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 6509

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.