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 to write Hello World in C++? ›

Every C++ program must have a main function. std::cout << “Hello, World!”;: This line outputs the text “Hello, World!” to the console. The std::cout is a predefined object in C++ that represents the standard output stream. return 0;: This line ends the main function and returns the value 0.

What is C++ programming with 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 do you write Hello World in code? ›

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 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 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.

What are the steps in writing C++ program? ›

  1. Step 1: Download and Install an IDE. ...
  2. Step 2: Commenting. ...
  3. Step 3: #include Directives. ...
  4. Step 4: Main Function. ...
  5. Step 5: Variables and Variable Types. ...
  6. Step 6: Printing to Console. ...
  7. Step 7: Reading From the Console. ...
  8. Step 8: Arithmetic Operations and Assignment Operator.

What's better Python or C++? ›

C++ duel lacks a clear winner, as the better choice depends on individual preferences and project requirements. Python excels in quick learning and the rapid development of small programs. In contrast, C++ is suitable for large projects and exploring multiple languages, although it requires more time to master.

Is C-plus-plus hard? ›

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.

What is C++ used for in real life? ›

What is C++ Used For? C++ (or “C-plus-plus”) is a general-purpose programming and coding language. C++ is used in developing browsers, operating systems, and applications, as well as in-game programming, software engineering, data structures, etc.

Why do programmers say Hello World? ›

A “Hello, world!” program is traditionally used to introduce novice programmers to a programming language. “Hello, world!” is also traditionally used in a sanity test to make sure that a computer language is correctly installed, and that the operator understands how to use it.

Why is Hello World so popular? ›

Why is Hello World so famous? "Hello, World!" is renowned as one of the most basic and traditional programming exercises. It's often the first program taught to beginners learning a new programming language.

What are the files used to write Hello World program? ›

There is an XML layout file and Java/Kotlin implementation file corresponding to each activity in our application. Refer to the blog Android Activity and Types on our Coding Ninjas Website to learn more about Android activities.

How to print Hello World in script? ›

  1. Using console. log() console. log() is used in debugging the code. ...
  2. Using alert() The alert() method displays an alert box over the current window with the specified message. Source Code. // the hello world program alert("Hello, World!" ...
  3. Using document. write() document.

How to print Hello World command line? ›

To print anything in a bash console, use the echo command followed by what is to be printed:
  1. $ echo Hello World Hello World. ...
  2. $ echo "Hello World" Hello World. ...
  3. $ echo 'Hello World' Hello World. ...
  4. $ printf "Hello World" Hello World$ ...
  5. $ printf "Hello World\n" Hello World. ...
  6. printf FORMAT [ARGUMENTS]

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 int main () in C++? ›

The int main() defines the entry or the starting point of the C/C++ program code. Here int is a keyword that tells us about the integer data type. So when one runs the file on their local computer, the operating system executes the main () function.

What is the introduction of 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.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Nathanial Hackett

Last Updated:

Views: 6403

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.