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

C-Strings

The C++ character string originated within the C language and continues to be supported within C++. In C programming, the char type is used to store characters. The char type is an integer type. Using a numerical code, each char integer value is mapped with a corresponding character. The most common numerical code is ASCII. 

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;

Char Arrays

C-strings are arrays of type char terminated with the null character or \0.

To Declare and Initialise a Character String Array

Character arrays can be declared and initialised on a character-by-character basis using an array-style initialiser however it’s much easier to initialise a character array with a string literal –

char greeting[6] = {'h','e','l','l','o','\0'}; // each array address is initialised individually with NULL character added manually

char greeting[] = "hello" ;//initialisation with a string literal with the compiler calculating the size of the array. The null character is added automatically.

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

Assign New Values to a Char Array

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 ie 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, C++ uses the function strcpy/strncpy (found in the string.h header) to assign the contents of an array outside of a declaration. The syntax for strcpy is-

strcpy(greetings,"hello");

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[31]="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<=31; i++) {
cout << *(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. Programmers can allocate their pointers to store and access characters held in string tables. The code sample below creates and prints a string literal –

#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;
}

Attempting to modify a string literal using a pointer can result in undefined behaviour so any pointer to a string literal should be declared constant.

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>
const int MAX = 7; 
int main () 
{ 
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;
}

wchar_t, char16_t, char32_t

A wchar_t, or wide char is similar to the char data type but is usually 2 bytes and can represent characters requiring more memory than a regular char data type such as the Unicode standard UTF-16LE.

Since the size of wchar_t is compiler-dependent it is better to use the dedicated data types char32_t and char16_ to ensure cross-compiler compatibility,

The char16_t and char32_t types represent 16-bit and 32-bit wide characters, respectively. Unicode encoded as UTF-16 can be stored in the char16_t type, and Unicode encoded as UTF-32 can be stored in the char32_t type.

The wcout object in C++ is an object of the class wostream and is used to send Unicode strings that do not fit in a char variable to the screen. To declare a wide-character string literal it is necessary to put L before the literal.

The following code demonstrates char and widechar arrays with the associated size data.

#include <iostream> 
#include <string.h>
#include<cwchar> 
using namespace std; 
int main() 
{ 
 char str[]="string";
// wide-char type array string 
 wchar_t wstr[]=L"string" ;
 cout << "The size of '" << str <<"' is " << sizeof(str) << endl;
 wcout << "The size of '" << wstr << "' is " << sizeof(wstr) << endl; 
 return 0; 
}

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 arraydata[50];

The arraydata 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 arraydata[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 arraydata[] = { 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 be declared. This variable declaration will specify to the compiler the name and type of a variable. The size of the data type will vary depending on the computer platform. Any attempt to use a variable that hasn’t been declared will result in the compiler generating an error message. A variable declaration will consist of the variable type followed by the variable name. Multiple single-line variable declarations are possible by separating each declaration with a comma –

int x //declares variable of type int float x,y,z; //declares variables of type float short int x,y,z; //declares variables of type short int unsigned int x,y,z; //declares variables of type unsigned int char xyz; //declares variable of type char

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 parenthesis ()

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 some 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 the 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++, programming 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 but if two variables are defined with different scopes this is not a problem. If a global variable is defined with the same name as a local variable, the local variable takes precedence. To access the global variable use the scope resolution operator. In CPP 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 provides a way to declare an identifier as an alias or shortcut for an existing variable type. The compiler substitutes the identifier with the variable type When compiled. Typedef does not create a distinctive variable type but establishes a synonym for an existing variable type 

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

Auto-Typed Variables

Specifies that the type of variable that is being declared will be automatically deducted from its initialiser. A programmer normally specifies the variable type at the variable’s creation however auto keyword in C++ enables a type to be inferred based on the value initially assigned to it. The compiler figures out a suitable data type –

auto count = 3;

The above statement creates the variable count to hold an int value.

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 numerator 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 the size of a variable or data type can differ between computing environments, knowing the size of a variable 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 maybe 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.

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 global static variables are still valid their use is not considered good programming practice. Using global variables via namespaces is the preferred method.

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 prevents the compiler from applying any optimisations to a variable. The syntax is –

volatile int value;  

Since a value might be changed by code outside the function scope, the system keeps the value of any variable or object current. For instance, the address of a global variable may be passed to an interrupt-driven event that updates a variable without the use of any explicit assignment statements in the program. If the CPP compiler is permitted to optimise certain code on the assumption that the content of a variable is unchanged then this can create problems.

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 that is typed directly into the source code such as a number, character, or string that may be assigned to a variable or symbolic constant. For instance, in the variable declaration count=10, the variable count is assigned the literal constant 10.

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 only, 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 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 bracket
    std::cout << "Hello World" << std::endl;   // Write to the screen 
    return 0;  // Return a value to the OS
    } //Closing bracket 

#include <iostream>

The first line in the code is called a preprocessor directive. The character # always precedes preprocessor directives. The preprocessor’s job is to search source code for directives and modify the code according to the indicated directive. The #include <iostream> directive tells the preprocessor that what follows is the name of a file from the standard library. The file contents are read into the program and the modified code is then fed to the compiler for compilation. The <iostream> header includes important code needed for reading the keyboard and writing information to the screen.

The angled brackets (< >) around the filename iostream tell the preprocessor to look in an explicitly specified compiler-specific location for the file. Using double quotes instead of angled brackets indicates that the current working directory should be searched for the required header file. C++ includes a standard library of classes and functions that are part of 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{}

Brackets or brace marks are used to group blocks of code. All functions begin with an opening brace { and end with a closing brace }. Everything between the opening and closing braces is part of the function scope.

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 a single line or can enclose 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 be ended 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