Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

C++ Syntax

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C++ Syntax

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

C++ Syntax

Let's break up the following code to understand it better:

Example
#include <iostream>
using namespace std;

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

Example explained
Line 1: #include <iostream> is a header file library that lets us work with input and
output objects, such as cout (used in line 5). Header files add functionality to C++
programs.

Line 2: using namespace std means that we can use names for objects and variables from
the standard library.

Don't worry if you don't understand how #include <iostream> and using namespace
std works. Just think of it as something that (almost) always appears in your program.

Line 3: A blank line. C++ ignores white space.

Line 4: Another thing that always appear in a C++ program, is int main(). This is called
a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with the insertion
operator (<<) to output/print text. In our example it will output "Hello World".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the code
more readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main function.

Omitting Namespace
You might see some C++ programs that runs without the standard namespace library.
The using namespace std line can be omitted and replaced with the std keyword, followed
by the :: operator for some objects:
Example
#include <iostream>

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

It is up to you if you want to include the standard namespace library or not.

C++ Output (Print Text)


The cout object, together with the << operator, is used to output values/print text:

Example
#include <iostream>
using namespace std;

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

You can add as many cout objects as you want. However, note that it does not insert a
new line at the end of the output:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}

New Lines
To insert a new line, you can use the \n character:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}

Another way to insert a new line, is with the endl manipulator:


Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

Both \n and endl are used to break lines. However, \n is used more often and is the
preferred way.

C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be
used to prevent execution when testing alternative code. Comments can be singled-lined
or multi-lined.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be
executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

Example
cout << "Hello World!"; // This is a comment
C++ Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments, and /*
*/ for longer.

C++ Variables
Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for
example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
 string - stores text, such as "Hello World". String values are surrounded by double
quotes
 bool - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

Syntax
type variable = value;

Where type is one of C++ types (such as int), and variable is the name of the variable
(such as x or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
cout << myNum;

You can also declare a variable without assigning the value, and assign the value later:

Example
int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous
value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

Other Types
A demonstration of other data types:

Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

Display Variables
The cout object is used together with the << operator to display variables.

To combine both text and a variable, separate them with the << operator:

Example
int myAge = 35;
cout << "I am " << myAge << " years old.";

Add Variables Together


To add a variable to another variable, you can use the + operator:
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

Declare Many Variables


To declare more than one variable of the same type, use a comma-separated list:

Example
int x = 5, y = 6, z = 50;
cout << x + y + z;

C++ Identifiers
All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as names

Constants
 When you do not want others (or yourself) to override existing variable values, use
the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are
unlikely to change:

Example
const int minutesPerHour = 60;
const float PI = 3.14;

C++ User Input


 You have already learned that cout is used to output (print) values. Now we will
use cin to get user input.

 cin is a predefined variable that reads data from the keyboard with the extraction
operator (>>).

 In the following example, the user can input a number, which is stored in the
variable x. Then we print the value of x:

Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

Good To Know

 cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)

 cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)

Creating a Simple Calculator


In this example, the user must input two numbers. Then we print the sum by
calculating (adding) the two numbers:

Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

C++ Data Types


As explained in the Variables chapter, a variable in C++ must be a specified data
type:

Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

Basic Data Types


The data type specifies the size and type of information the variable will store:

Data Size Description


Type

Int 4 Stores whole numbers, without decimals


bytes

Float 4 Stores fractional numbers, containing one or more decimals. Sufficient


bytes for storing 7 decimal digits

Double 8 Stores fractional numbers, containing one or more decimals. Sufficient


bytes for storing 15 decimal digits

Boolean 1 byte Stores true or false values

Char 1 byte Stores a single character/letter/number, or ASCII values


Numeric Types
Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like 9.99 or
3.14515.

int
int myNum = 1000;
cout << myNum;
float
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;

float vs. double

The precision of a floating point value indicates how many digits the value can have after
the decimal point. The precision of float is only six or seven decimal digits,
while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.

Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of
10:

Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

Boolean Types
A boolean data type is declared with the bool keyword and can only take the
values true or false. When the value is returned, true = 1 and false = 0.

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

You might also like