Your browser doesn't support JavaScript cpp Archives - Page 3 of 3 - Windows Programming

C-Strings

The C++ character string originated in the C language and continues to be supported within C++. In C programming, the char type is used to store characters. char is an integral type that is used to represent a character. It is stored as a small integer value, and the mapping between character values and characters depends on the character encoding used.

To declare a variable with character type, use the char keyword followed by the variable name –

char ch;

Initialise a char

A char character variable can be initialised with a character literal or an integer type. A character literal contains one character surrounded by a single quotation (‘’).

The following example declares  char variable ch and initialises it with a character literal ‘A’

char ch='A';

Because a char is an integer type, it can also be initialised using an integer. –

char ch=65;

Character Arrays and C-Strings

In C++, a character array is an array of type char that stores a sequence of characters. Character arrays are commonly used to store text, but not every character array is a C-string.

A C-string is a character array that ends with a special character called the null character, written as '\0‘. This character marks the end of the string.

For example:

char letters[5] = {'H', 'e', 'l', 'l', 'o'};

This declares a character array containing five characters. However, it is not a C-string because it has no terminating null character.

To create a C-string, the array must include space for the null character:

char word[] = "Hello";

The compiler automatically adds the terminating '\0', so the array contains six characters in total: the five letters and the null character.

Initialising a char array with the value ‘\0’ creates a NULL or empty string – 

char greeting[0] = {'\0'};

Inserting ‘\0’ anywhere in the middle of the array would not change the size of the array but it would mean that string processing would stop at that point. Sending the following char array to the screen would only produce the characters ‘hel’

char greeting[] = "hel\0lo" 

Single Quotes vs Double Quotes

In C++ single quotes identify a single character and double quotes creates a string literal. ‘a’ is a single character literal, while “a” is a string literal containing an ‘a’ and a null terminator (that is a 2 char array).

Assigning a new value to a String

To change the contents of the string after the initial assignment, it is necessary to change the array contents individually. Trying to assign a new value to an existing char array, i.e. greetings[]=”HELLO”, won’t work because the = operator isn’t defined to copy the contents of a string literal to a char array.

greetings[0] = ‘H’;
greetings[1] = ‘E’;
greetings[2] = ‘L’;
greetings[3] = ‘L’;
greetings[4] = ‘O’;
greetings[5] = ‘\0’;

Since assigning new array string values individually is not very practical, The C-style functions strcpy and strncpy can be used to copy characters into an existing character array. They are declared in <cstring>.

strcpy(greetings,"hello");

Important: the destination array must have enough space. strcpy does not check the size of the destination array.

Pointers and Arrays

The use of pointers can also access array elements. The pointer is declared and assigned to the first element of the array. After assigning the array pointer, the individual elements can be accessed by increasing or decreasing the pointer value.

The code section below outputs the same letters of an array string by using pointers and array indexing

#include <iostream>
using namespace std;
int main()
{
char str[30]="this is a string to array test"; //declares char arrar
char *pChar=str;//declares char pointer and sets to start of array
int i;
for (i = 0; i < sizeof(str); i++){
cout << static_cast<void*>(pChar + i); //outputs pointer value
cout << str[i] ; //outputs array value
}
return 0;
}

Pointers and String Literals

A string literal in C++ is a sequence of characters enclosed in double quotation marks. For example, “Hello World” is a string literal.

String literals must not be modified. Therefore, when a pointer is used to access a string literal, it should point to const char, indicating that the characters cannot be changed through that pointer.

The following example creates a pointer to a string literal and prints its contents:

#include <iostream>
using namespace std;
int main()
{
const char *ptrsl= "this is a string literal."; //creates pointer ptrsl to to start of string array
cout << ptrsl;
return 0;
}

Array of Pointers

An array of pointers to strings is a sequence of char pointers where each pointer points to the first character of a sequence of strings. To declare and initialise an array of pointers to strings.

char *day[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday","Saturday"};

Since initialisation of the array is done at the time of declaration then the size of the array can be omitted.

To access the values pointed to by an array of pointers it is necessary to iterate and de-reference each pointer individually.

In the code section below, each element of the array day is a pointer to the base address of the first character of an individual string literal which is then output using a for-next loop.

#include <iostream>
#include <cstdio>
const int MAX = 7; 
int main () 
{ 
const char *day[] = {"Sunday","Monday","Tuesday", "Wednesday", "Thursday","Friday","Saturday"}; 
int i = 0; 
for ( i = 0; i < MAX; i++){
printf("day[%d] = %s\n", i, day[i] ); 
}
return 0;
}

Wide Character Types

In C++, wchar_t, char16_t, and char32_t are character types designed to represent character data using different character encodings and code-unit sizes. They can be useful when working with text that requires Unicode encoding.

A wchar_t, or wide character, is an implementation-defined character type. Its size and the encoding used to represent characters depend on the platform. On Windows, it is normally 16 bits wide, while on Linux it is normally 32 bits wide.

Because the size of wchar_t is platform-dependent, C++ also provides char16_t and char32_t as fixed-width character types. char16_t is 16 bits wide and is commonly used for UTF-16 encoded text, while char32_t is 32 bits wide and is commonly used for UTF-32 encoded text.

The wcout object is an instance of the std::wostream class and is used to output wide-character data to a stream, typically the console. However, it does not automatically guarantee correct Unicode output; the result depends on the stream configuration and platform.

To declare a wide-character literal, place the prefix L before the literal. For example:

#include <iostream>
using namespace std;

int main() {
    wchar_t letter = L'A';
    wcout << letter << endl;
    return 0;
}

In this example, L‘A’ is a wide-character literal, and wcout outputs the character.

The prefixes u and U are used for UTF-16 and UTF-32 literals, respectively:

char16_t letter16 = u'A'; char32_t letter32 = U'A';

Note: char16_t and char32_t represent UTF code units, not necessarily individual user-perceived characters. For example, some Unicode characters require two UTF-16 code units.

Arrays

An array in CPP is a data structure for storing related information of the same data type. Each storage location in an array is called an array element and is identified by an array index or key. The lowest index address corresponds to the first element and the highest index address to the last element.

Declare an array

The declaration statement for an array is similar to the one used to declare any other variable. An array is declared by writing the data type and array name followed by the number of elements the array holds inside square brackets –

int data[50];

The data array (above) holds 50 sequential int integers. This declaration causes the compiler to set aside enough memory to hold all 50 elements. If each integer requires 4 bytes, the array declaration will reserve 200 contiguous bytes of memory. Array elements are numbered from 0 to the largest element, or 0 to 49 in the case of the array arraydata. Any attempt to initialise more elements than you’ve declared for the array generates a compiler error. 

Initialising Arrays

An array can be initialised by using a list of comma-separated values enclosed in braces:

int data[10] = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

If the size of the array is omitted, an array just big enough to hold the initialisation values is created.

int data[] = { 10, 20, 30, 40, 50 };

The built-in C++ function sizeof() can be used to count the number of elements in an array:

const int size = sizeof(arraydata) / sizeof(arraydata[0]);

Accessing Data Stored in an Array

An element is accessed by indexing the array name. This is done by placing the element index within square brackets after the array name. These indexes are called zero-based because the first element in an array is at index 0. The first integer value stored in an array arraydata[10] is arraydata[0], the second is arraydata[1], and so on. The index of the last element in an array is always (Length of Array – 1) or arraydata[9].

Multidimensional Arrays

Although, in theory, an array can have any number of dimensions, it is rare to have more than two dimensions. When an array is declared, each dimension is represented as a subscript in the array.

If an array can be considered a single row of data then a two-dimensional array could be pictured as a table of data consisting of rows and columns or a list of rows. A three-dimensional array could be a cube, with one dimension representing width, a second dimension representing height, and a third dimension representing depth.

A two-dimensional array has two subscripts:

int array[5, 13];

A three-dimensional array has three subscripts:

int cube[5, 13, 8];

Initialising Multidimensional Arrays

Multidimensional arrays can be initialised with values just like single-dimension arrays. Values can be assigned using nested braces, with each set of numbers representing a row as below –

3 different ways to initialise a two-dimensional array.

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[2][3] = {1, 3, 0, -1, 5, 9};

Initialisation of a three-dimensional array.

int test[2][3][4] = {{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }}

Variables and Constants

A variable is a named location in computer memory where a program can store and retrieve a value. The value of this variable can be changed one or more times during the execution of a program. 

Defining Variables

Before a variable can be used in a program, it must normally be declared. A variable declaration tells the compiler the name and type of the variable.

The type of a variable determines what kind of value it can store and, where applicable, how much memory is required to represent that value. The size of some C++ data types can vary between computer platforms and implementations.

Any attempt to use a variable that has not been declared and is not otherwise available in the current scope will normally result in the compiler generating an error.

A variable declaration consists of a type followed by one or more variable names. For example:

int age;

This declares a variable called age that can store an integer.

Multiple variables of the same type can be declared in a single statement by separating their names with commas:

int age, height, weight;

Each variable can also be given an initial value when it is declared:

int age = 25, height = 180, weight = 75;

The variables in this example are all of type int and are initialised with the values shown.

Rules for Naming Variables in CPP

  • All variables must begin with a letter of the alphabet or underscore.
  • Although variable names can be alphanumeric, they cannot start with a number.
  • Uppercase characters are distinct from lowercase characters.
  • Variable names cannot be C++ reserved keywords.

Initialising Variables by Assigning Values

A variable can be assigned an initial value when it is created or assigned a value after creation but these values must be in the correct format. In C++, there are three ways to initialise a variable –

Using the assignment operator (=)

int value=10; //creates and initialises variable value of type int

Using parentheses ()

int value (20) ; //creates and initialises variable value of type int to 20

Using braces {}

int value{30} ; //creates and initialises variable value of type int to 30

An uninitialised variable is a variable that is declared but will have an unknown value known as a “garbage value”. This is due to the compiler assigning a memory location and the variable inheriting whatever value is already in that memory location. Using the value from an uninitialised variable can result in undefined behaviour. Undefined behaviour means executing code whose behaviour is not well defined resulting in data corruption.

Variables declared with a global scope or declared static are initialised to zero. This is because global or static variables are allocated in a separate part of memory and exist throughout the whole lifetime of the program.

Variable Types

Integer variables hold values that have no fractional part. Signed Integer variables can hold positive or negative values, whereas unsigned integer variables can hold only positive values. Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don’t have this bit, so the largest number stored in an unsigned integer is twice as big as the largest positive number in a signed integer. The supported data types in C++ are –

Data typeNotes
charCan store -127 to 127 or 0 to 255. 8 bits. Usually used for holding ASCII characters.
char16_tUnsigned integer type. Usually 16 bits. Used for UTF-16 character representation.
char32_tUnsigned integer type. Usually 32-bit bits. Used for UTF-32 character representation.
wchar_tOccupies between 16 or 32 bits depending on the compiler being used. Used for Unicode character representation.
signed char8 bits. Can store values between -128 to +127. Used for dealing with binary data.
signed short intUsually at least 16 bits. Can store values between –32,768 to 32,767.
signed intUsually at least 16 bits. Can store values between –32,768 to 32,767.
signed long intUsually at least 32 bits. Can store values between –2,147,483,648 to 2,147,483,647.
signed long long intusually at least 64 bits. Can store values between –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
unsigned char8 bits. Can store values between 0 to 255.
unsigned short intAt least 16 bits. Can store values between 0 to 65,535.
unsigned intAt least 16 bits. Can store values between 0 to 65,535.
unsigned long intAt least 32 bits. Can store values between –2,147,483,648 to 2,147,483,647.
unsigned long long intAt least 64 bits. Can store values between 0 to 4,294,967,295.
floatUsually 32 bits. Used for storing single precision floating point values.
doubleUsually 64 bits. Used for storing double precision floating point values.
long doubleUsually 96 bites. Used for storing long double precision floating point values.
bool1 byte. Used to represent True of False where true = 1 and false = 0.

Variable Scope

The scope of a variable refers to the accessibility of a variable in a given program or function. Any attempt to reference a variable outside its scope will generate a compiler error.

In C++, variables can be declared in three places:

  1. Inside a function or a code block. These are local variables and are only valid inside the block they are defined. When a local variable is defined, it is not initialised by the system and must be initialised by the program.
  2. Outside of all functions. These are global variables and can be accessed in any part of the program.
  3. In the function parameters (formal parameter).

In the code example below an attempt to reference an out-of-scope variable will cause the compilation to fail.

#include <iostream>
using namespace std;
int globalvariable = 0;  //global variable declaration and value assignment
main()
{
{   // create local scope by use of brackets
int localvariable = 1;//local variable declaration and value assignment 
globalvariable = 1; //assign value 1 to global variable
} // end local scope by use of brackets 
globalvariable = 2; // assign value 2 to global variable 
localvariable = 2; // will not compile. local variable not defined in this scope
}

Clashes in Scope

Usually, when two variables are defined with the same name in the same scope, the compiler produces a compile-time error. However, if two variables are defined in different scopes, this is not a problem.

If a global variable has the same name as a local variable, the local variable takes precedence within its scope. To access the global variable, use the scope resolution operator.

In C++, the scope resolution operator is ::.

#include <iostream>
using namespace std;
int v = 0; //create global variable v and assign value 0 
main() { 
int v = 1; //create local variable v and assignment value 1 
::v=2; //set value of global variable i to 1 
}

Using Type Definitions

The typedef declaration allows a programmer to create an alias, or alternative name, for an existing data type. The compiler treats the alias as a synonym for the original type. typedef does not create a new, distinct data type; it simply provides another name for an existing type.

For example, the following statement defines Counter as an alias for int.

typedef int aliasint; //create an alias for int name aliasint aliasint v=12; //creates int variable v and set to 1

Auto-Typed Variables

The auto keyword in C++ allows the compiler to automatically deduce the data type of a variable from its initialiser. Normally, a programmer specifies the variable’s type when declaring it. However, when auto is used, the compiler determines the appropriate type based on the value assigned to the variable.

The following statement creates a variable called count. Since it is initialised with an integer value, the compiler deduces its type as int.

auto count = 3;

Enumerations

An enumeration is a user-defined data type that consists of integral constants called enumerators. An enum variable takes only one value out of many prescribed values and returns a numeric value corresponding to the selected enumeration. These constants can then be used anywhere that an integer can.   Enumerations are defined using the keyword enum followed by the type name and then the variable list.

The enumeration list is a comma-separated list of names representing the enumeration values. The variable list is optional because variables may be declared later using the enumeration type name. Although enumerated constants are automatically converted to integers, integers are not automatically converted into enumerated constants.

The following code declares an enumerator called user with values: John, Peter, Mark and Paul, followed by an enumerator variable named id. The enumerator variable is set to each name and the integer value output. If no value is set for the enumerated constant, then the value of the previous constant is increased by one.

#include <iostream>
enum users{John=1, Peter, Mark=7, Paul}; //declare enumerator & set enumerator list values
int main(){
users id;//declare eumerator type declaration variable id
id=John;//set variable id to John
std::cout << "user id "<< id;//output value of John which is 1
id=Peter;//set variable id to Peter
std::cout << " user id "<< id;//output value of Peter which is 2 (1 more than John)
id=Mark;//set variable id to Mark
std::cout << " user id "<< id;//output value of Mark which is 7
id=Paul;//set variable id to Paul
std::cout << " user id "<< id;//output value of Paul which is 8(one more than Mark)
return(0);
}

Sizeof

The operator sizeof indicates the size in bytes of a variable or a type. Since variable size or data type can differ between computing environments, knowing the variable size in all situations can be useful. The syntax of using sizeof is as follows −

sizeof (data type)

Static Variables

Variables of type static are permanent variables within their function or file.  A static variable is declared by putting the word static before the variable type and may be initialised with a value. 

static int days = 7; //declare static variable 'days' and initialises to 7

Static variables, like global variables, are initialised to 0 if not explicitly initialised to a defined value.

The scope and visibility depend on where they are declared.

Static Local Variables – When the static modifier is applied to a local variable, permanent storage is allocated, allowing a static variable to maintain its value between function calls. Local static variables are initialised only once, when program execution begins, and retain their value between function calls.

Static Global Variables – A static global variable is known only to the file in which the static global variable is declared. This means other functions in other files have no knowledge of it and cannot change its contents. Although static global variables are still valid, their use is not considered good programming practice. Using global variables via namespaces is preferred.

The program below calls the function svar() twice, outputting the value of variable count twice and increasing the value by 1.

#include <iostream>
using namespace std;
void svar();//declare variable function
int main()
{
int num;
svar();//call variable function
svar();//call variable function
return 0;
}
void svar() {
static int count=5;//declares and initialises static local variable
cout << count;//output variable value
count++;
}

Extern

The extern keyword enables the programmer to declare a variable without defining it. In programs with several files, each file must be aware of the global variables defined outside that file. The extern declaration informs the compiler that a variable by that name and type already exists therefore, the compiler does not need to allocate memory for it since it is allocated elsewhere. The syntax is –

extern int x,y;

Although global variables are generally declared at the top of a program, declaring variables as extern has the benefit of enabling global variables to be declared anywhere.  If a function uses a global variable defined later in the same file the global variable can be declared as extern inside the function. When the variable’s definition is encountered, references to the variable are resolved –

#include <iostream>
using namespace std;
extern int count;//extern tells compiler to look for definition elsewhere
int main()
{
cout << count;
return 0;
}
int count=5; //global variable declared after main block

Volatile Variables

The volatile keyword tells the compiler that a variable’s value may change unexpectedly due to factors outside the normal flow of the program. The compiler must therefore ensure that accesses to the variable are performed as required by the language rules, rather than assuming its value remains unchanged.

The syntax is:

volatile int value;  

The volatile keyword is useful when working with memory-mapped hardware registers or variables that may be modified by certain external mechanisms, such as hardware or interrupt handlers.

For example, if an external event changes a variable, the compiler must not simply assume that the variable still holds its previous value when the program reads it again. Without appropriate handling, optimisations based on that assumption could cause the program to behave incorrectly.

However, volatile does not make operations atomic and does not provide thread synchronisation. In C++, it is not a substitute for atomic variables or mutexes when sharing data between threads.

Constants

Constants or literals refer to fixed values a program may not alter after their definition. C++ has two types of constants:

  • Literal Constants
  • Symbolic Constants 

Literal Constants

A literal constant is a value written directly into the source code. Examples include numbers, characters, and strings.

For example:

int count = 10; char letter = 'A'; std::string message = "Hello";

In these declarations:

  • 10 is an integer literal.
  • ‘A’ is a character literal.
  • “Hello” is a string literal.

Symbolic Constants

A symbolic constant is an identifier representing a constant value for the program duration.  Whenever a constant value is required the constant name can be used in place of that value throughout the program thus the value of the symbolic constant only needs to be entered when it is first defined. Symbolic constants can be defined using the preprocessor directive #DEFINE or the const keyword.

Defining Constants Using #define –The #define directive enables a simple text substitution that replaces every instance of the name in the code with a specified value with the compiler only seeing the final result.  Since these constants don’t specify a type, the compiler cannot ensure that the constant has a proper value so it’s better to use the standard constant method. Defining constants using the preprocessor directibe dates back to early versions of the C language.  It is now depreciated and should not be used. The prototype of the define directive is –

#define PI 3.14

Defining Constants with the Const Keyword – means declaring a variable with a const prefix.  Variables declared to be const can’t be modified when the program is executed. A value is initialised at the time of declaration and is then prohibited from being changed. 

PI is declared as a const variable and a preprocessor directive in the following code.

#define PI 3.14 //set value of constant directive
#include <iostream>
int main()
{
const float PIVALUE= 22.0 / 7; //set value of constant
printf( "\nValue of constand variable PI %f", PIVALUE);
printf( "\nValue of constant directive PI %f", PI);
return 0;
}

Constants are often fully capitalised by programmers to make them distinct from variables. This is not a requirement but the capitalisation of a constant must be consistent in any statement since all variables are case sensitive.

Program Structure – the Basics

A Simple Piece of C++ Code

#include <iostream> //Preprocessor directive 
int main() // Start of your program: function block main()
{ //Opening brace
std::cout << "Hello World" << std::endl;   // Write to the screen 
return 0;  // Return a value to the OS
} //Closing brace 

#include <iostream>

The first line in the code is called a preprocessor directive. The character # always precedes preprocessor directives. The preprocessor processes these directives before the source code is passed to the compiler.

The #include <iostream> directive tells the preprocessor to include the contents of the standard C++ iostream header. This header provides declarations for C++ stream-based input and output, including objects such as std::cout, std::cin, and std::cerr.

The angled brackets (< >) around the header name tell the compiler to search for the header using the implementation’s standard include paths. Double quotation marks (" ") are normally used when including a header from a project or other location specified by the implementation’s include search rules.

C++ includes a standard library of classes, functions, objects, and other facilities defined by the C++ ISO Standard.

Int main()

Every C++ program includes the function int main() and can have only one main() function. When a program starts, main() is called automatically and marks the entry point for the program. Main() cannot be called from within a program. The body of the main() function does not need to contain a return statement; if control reaches the end of the main block the effect is that of a return 0.  Main() can also accept two command line arguments: argv and argc used to pass parameters from the calling environment.

Braces{}

Braces are used to group statements into a block (also called a compound statement). In a function definition, the opening brace { marks the beginning of the function body and the closing brace } marks its end.

Everything between the opening and closing braces forms part of the function body.

For example:

{   std::cout << "Hello World"; }

Braces are also used in many other parts of C++, including if, for, and while statements, as well as classes and other constructs.

Std::cout

cout stands for console out and is used to write simple text data to the console. The designation std:: instructs the compiler to use the standard C++ input/output library.    The standard output operator << causes whatever expression is on its right side to be output to the device specified on its left side. The output operator can be used multiple times in a single cout statement to display separate character strings.

Return 0 

Terminates main() and causes it to return the value 0 to the calling process which is typically the operating system. Functions in C++ need to return a value unless explicitly specified otherwise. Function main() always returns an integer. A return value of 0 signifies that the program is terminating normally. Other values indicate that the program is terminating because of some error. All C+ programs should return 0 when they terminate normally.

Comments

Comments are lines of text not evaluated by the compiler and are used by programmers to explain their code. Comments are either single lines or blocks of text.

A single-line comment begins with two slash marks ( // ) and causes the compiler to ignore everything that follows the slashes on the same line as follows –

//this is a comment

A multiple-line comment begins with the backslash and asterisk character ( /* ) and ends with the same characters reversed ( */ ). Everything enclosed is a comment –

/*  this is a comment  */

Semicolons and Positioning

In C++, the semicolon is a statement terminator. Each statement must end with a semicolon since C++ does not recognise the end of the line as a terminator. A block is not terminated with a semicolon as a block is used to group statements. Several statements can be included on one line as long as each statement is terminated with a semicolon.

C++ overview

The C++ programming language was created by Bjarne Stroustrup in 1983. In 1985, the first edition  was released, and in 1998 it was standardised by the International Organizations of Standardization (ISO). So far there have been five revisions to the C++ standard with the next scedules revision coming in 2020.

C++ is considered a middle-level language, comprising of both high-level and low-level language features. C++ is a superset of C. This means that virtually any functional C program is a legal C++ program.

ANSI-C++ is the name for the ANSI/ISO agreed internationally sandardised version of C++. Prior to this standardised version C++ was already widely used by did not adhere to any pre agreed format. Pre-standard C++ code may be incompatible in some ways with the standard version.

C++ is a compiled language – meaning that source code is translated directly to machine code and not interpreted ar run time line by line. Programs compiled into native code at compile time tend to be faster than those translated at run time, due to the overhead of the translation process.

Visual C++ Is a platform that implements that standard version of C++ in additional to adding some Microsoft specific extensions. Programs can be written in portable standard c++ but using any Microsoft specfic extensions will underine any portability

Windows programming – Since windows programs do not generally use the console to communicate with the user, any programming for an widowed environment will need to utilize the set of functions or classes specially created for that OS

Some C/C++ compilers

Visual studio community edition>
NetBeans IDE>
Eclipse IDE>
Dev C++
Code Blocks