c & c++ - C++ Language

Contact
PC-compilers
last-news
PIC-microcontroller
AVR-microcontroller
Supports
weakly newsletter
c++
=> Visual Studio
=> C++ Language
=> arrays
=> Functions
=> Windows Programming
=> Using AppWizard
=> MFC Model
Counter
DS1821Thermostat Programmer
pic-asm-foundations
free links downloads
free downloads
mikroc library
PWM software
Home



 

C++ Language

The C++ lanuage features are immense.  Ponder on the fact that the Windows NT operating system, or for that matter the Microsoft Word application, is written in C++.   You can create C++ applications in  procedural style or in an object oriented manner.  In the short time we have here we can only look at some select features.  You are stronly encouraged to consult other extensive documentation for increased exposure to a wealth of features.  The first important issue in writing working code is to avoid using Keywords for names in your program.
 

Keywords

C++ Keywords

Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program. The following keywords are reserved for C++:

asm1    auto    bad_cast    bad_typeid    bool    break    case    catch    cha    class    const    const_cast    continue    default    delete    do    double    dynamic_cast    else    enum    except    explicit    extern    false    finally    float    for    friend    goto    if    inline    int    long    mutable    namespace    new    operator    private    protected    public    register    reinterpret_cast    return    short    signed     sizeof    static    static_cast    struct    switch    template    this    throw    true    try    type_info    typedef    typeid    typename    union    unsigned    using    virtual    void    volatile    while    xalloc

Microsoft Specific ®  ( To keep your source portable you may not want to use these)

In Microsoft C++, identifiers with two leading underscores are reserved for compiler implementations. Therefore, the Microsoft convention is to precede Microsoft-specific keywords with double underscores. These words cannot be used as identifier names.

allocate3    __inline    property3    __asm1    __int8    selectany3    __based2    __int16    __single_inheritance    __cdecl    __int32    __stdcall    __declspec    __int64    thread3    dllexport3    __leave    __try    dllimport3    __multiple_inheritance    uuid3    __except    naked3    __uuidof    __fastcall    nothrow3    __virtual_inheritance    __finally
 
 

Microsoft extensions are enabled by default. To ensure that your programs are fully portable, you can disable Microsoft extensions by specifying the ANSI-compatible /Za command-line option (compile for ANSI compatibility) during compilation. When you do this, Microsoft-specific keywords are disabled.

When Microsoft extensions are enabled, you can use the previously-listed keywords in your programs. For ANSI compliance, these keywords are prefaced by a double underscore. For backward compatibility, single-underscore versions of all the keywords except __except, __finally, __leave, and __try are supported. In addition, __cdecl is available with no leading underscore.

Ref: VS Documentation

Data Types

The fundamental data types in C++ are:
 
 

Data Type

Storage Range

bool

 

true or false (promoted to 1 or 0)

char

1 byte.  There are signed char and unsigned char types too.

ANSI character set (0 to 255)

int

4 bytes . There are short, long, unsigned short, unsigned, and unsigned long variations in the int type

int is 4 bytes. rest adjusted by add or subtract 2 bytes.  Range: -32,768 to 2147483647

float

4 bytes or 2 words.  The variations in this type are double (8 bytes/4 words) and long double ( 10 bytes or 5 words)

double: - 1.7e-308 to +1.7e+308. long double: -+1.18e-+4932

wchar_t

a new definition for character sets from 

other languages

void

0 bits or no value

used to create pointers

pointer

the pointer (new to us) contains  the address of the memory location holding the actual data

A pointer is defiend by the asterisk at the end of type declaration and before the variable name 
int* a;

 

Variable names/Identifiers

A Variable name can have one or more letters,digits and underscore.  Only the first 31 characters are recognized

C++ is case sensitive

Avoid using leading underscore to prevent conflict with system variables

Two leading underscores are reserved for C++ implementation and libraries

For code readibility it is recommended that you precede your variable name by a letter idicating the data type

Variable names cannot have the same spelling as keywords

Constants

Constants can be of the type defined above

Character constants are given in single quotes     'a' ,     'B',     '7',     '\n' etc.

Some special character constants use as escape sequence:

'\a'           alert
'\\'            backslash
'\b'           backspace
'\r'            carriage return
'\'''            double quote
'\f'            formfeed
'\t'            tab
'\n'           newline
'\''            single quote
'\v'           vertical tab

The character constants can be defined in octal, hexadecimal notations too.

Strings in C++ are character arrays.  There is no basic string data type.  The string is usually terminated with a null character '\0'.  So this makes the length of the string one more than the number of character it contains.
For example  to define and initialize a string constant     - A String -     we can use
        char str1[]  = "A String"        or
        char str2[9] = {'A',  ' ',  'S',  't',  'r',  'i',  'n',  'g',  '\0' }
        char str3[] = ""        - an empty string containing '\0'
        char str4[] = " This string stretches over \
                                two lines"
The last example indicates string continuation.  Also strings seperated by white space are implicity concatenated

For integer and float constants, the suffixes (u or U) , (l or L)(f or F)  indicate unsigned, long and float types respectively

Examples 101,  899u,  3.14f,  3.14156L,  .314e+1

Enumerations define a collection or list of identifiers or named constants.  The list is called an enumeration set.
        enum {order1, order2, order3}    // by definition the list inside the brackets take the
                                                        // vaue 0, 1, 2

        enum grades{F = 50, D = 60,  C = 70,    B = 80, A = 90} student
        The type of data is  grades
        The enumeration set is the list in the brackets
        The enumerated variable is student

Constants can be defined in C++ by using the const  keyword.
 

    const   int  order = 3;

Data Conversions

Automatic Converions

These are implicit conversions.  The compiler will automatically convert variables before operating on them. For example if

fltvalue1 =  fltvalue2 * intval1;

intval1 will be promoted automatically to a  float and then multipled with fltvalue2 and the result assigned to fltvalue1.   Note that the value of intval1 does not change.

Typically variables are promoted upwards.  The precedence or the hiearchy of the variables are:

int  <  unsigned <  long  <  unsigned long  <   float  <  double  <  long double.  int has the lowest precedence
 

Explicit conversions

Explicit conversions are done using the cast operation like Java

dblvalue1 =  dblvalue2 * (double) intval1;            or        C form

dblvalue1 =  dblvalue2 * double(intval1);            or        C++ functional form

dblvalue1 =  dblvalue2 * static_cast<double>(intval1);        ANSI C++

Operators

Many of the operators are the same you saw in Java, including the shortcut operators.  A quick review

Arithmetic

-a            unary minus
a * b        binary multiplication
a / b        binary division
i % 2     modulus  -- remainder of an integer division
a + b      binary addition
a - b       binary subtraction

In the above the precedence decreases down the list.  Sam colors indicate same precedence.

Relational and Logical Operators

<                    less than
>                    greater  than
<=                 less than or equal to
>=                greater than or equal to

==                equal to
!=                 not equal to

!                    unary negation
&&                logical and
||                    logical or

The logical operators are evaluated in shortcut fashion.  Unlike Java you cannot force evaluation of both expressions.  These operators should yield true or false (if bool is implemented) or 1 or 0.

Like Java there is a tertiary conditional operator:
 
    expression1  ?  expression 2 : expression 3
expression 1 is evalulated first.  If it is true then expression 2 is executed.  If not expression 3 is evaluated

Shortcut assignment operators

The autoincrement and autodecrement operators to change values by 1

j =  ++i;        translates to        i = i + 1; j = i;

j = i++ ;        translates to        j = i;  i = i + 1 ;

j = --i            translates to        i = i - 1; j = i ;

j = i -- ;        translates to        j = i ; i = i - 1 ;

These are also referred as post-increment and pre- increment operators

C++ allows multiple assignments in a statement

        no_vertex = 1 + (order = 3);

C++ has similar shortcut assignment operators that you saw in Java.

        a     op=  b;            This is equal to         a = a op b          for eg:
        a *=  a + b;            is equivalent to a = a * ( a + b);
op can represent any arithmetic operator

Other expressions

Comma operator:

        expression 1 , expression 2

The expressions are evaluated in sequence from left to right.  The result is the value and typeof expression 2

pointer and address operator
 
    int order = 3;                                // order  is declared and initialized to 3
 
    int *  value  =   &order ;               // value is a pointer to a data of type integer
                                                          //  &order  yields the location where a is stored
                                                          //  the statement means that value is pointing to  order

    *value  =  4;                                    // *value retrieves the value from the location being pointed at and assigns it
                                                            // order now is equal to 4
 
    order = *value  +  1;                        //order  will now have the value 5

what you have is pointer arithmetic.  Remember pointer only stores addresses of the appropriate type.  The  operator is sometimes called indirection operator,  The & is the address operator

sizeof() operator
    The size of operator give the size in bytes of whatever iss in the paranthesis.

new/delete
    The new and delete operators have to do with storage

bitwise operators:
    see documentation

This is getting dry.  Let us explore our next C++ program - checking out input/output

Ioex1.cpp

In this piece of code we will

    read from and write to the screen
    read from and write to a file
    define variables
    format output

/*
//  C++ program for examining
// screen and file input/output
//
*/

#include <iostream.h>  // library files for input and output
#include <iomanip.h>   //  library for manipulating I/O
        //  like setting precision, word length etc

#include <fstream.h>   //  file input anf output library
 

int main()      // the main function returning integer

{ int order, no_vertex;  // multiple declaration on a line
 double x1;
 double x2;
 double x3;
 double x4;
 
 double y1,y2,y3,y4;

 ifstream finput("C:\\Emem899\\Visual C++\\yvert.dat", ios::in);
 if(!finput)
  cerr << "\nUnable to open C:\\Emem899\\VC++\\yvert.dat for input.";
 // finput is a data input stream
 // associated with the identified file
 // why the double slashes ??

 // If file does not exit there will be an error
 // This error is wriiten to screen by cerr ( like cout) but
 // the program will stop

 ofstream foutput;
 
 // foutput is a data output stream
 // we will associate this with a file later
 

 cout  << " Enter the order of the curve:  ";  // writes the string to the screen
  // the  <<  is an overloaded operator in " iostream.h" that recognizes
  // what data type it is writng
 
 cin >> order;  // stores what you input in the variable order

 cout << "\n You entered  a value of " << order << endl;
 // prints the value you just entered
 

 cout << "\n";  // puts in a line as seperator

 // Since we are stuck with the cubic Bezier curve
 // we are going to read the x vertices from the screen and the
 // y vertices from a file

 cout << " read the first x-vertex:  ";
 cin  >> x1;
 cout << "\n The x-value of the first vertex is " << x1 << endl;

 // the default precision for real values is  6 digits or
 // less

 cout << " read the second x-vertex:  ";
 cin  >> x2;
 cout.setf(ios::showpos);
 cout << "\n The x-value of the second vertex is  :"  << x2 << endl;
 cout.unsetf(ios::showpos);

 //  above you can print the ' + ' character in front of values
 //  you use the set format function  setf()
 //  you need to unset it after use
 

 cout << "\n";

 cout << " read the third x - vertex:  ";
 cin  >> x3;
 cout << "The x-value of the third x-vertex:  ";
 cout.width(20);
 cout.fill('0');
 cout << x3 << endl;
 cout << "\n";

 //  set the width to 20 characters and fill with 0's

 cout << " read the fourth x - vertex:  ";
 cin  >> x4;
 cout.precision(9);
 cout << "The x-value of the fourth x-vertex : " << x4 << endl;

 // set the precision to 9 digits

 // NOTE:  The modifications to the format are ONLY
 //        valid for the next variable output

 ///////////////////////////////////////////////////////
 //   read from a file
 /////////////////////////////////////////////

 finput >> y1;

 // note you can use finput/foutput like cin/cout
 
 cout << "\nThe first y-vertex is :  " << y1 << endl;

 finput >> y2;
 cout << "\nThe second y-vertex is :  " << y2 << endl;

 finput >> y3;
 cout << "\nThe third y-vertex is :  " << y3 << endl;

 finput >> y4;
 cout << "\nThe fourth y-vertex is :  " << y4 << endl;

 foutput.open("C:\\Emem899\\Visual C++\\Ioex1.dat", ios::out);

 // here we have  associated foutput with the file
 
if(!foutput)
  cerr << "\nUnable to open C:\\Emem899\\Visual C++\\Ioex1.dat for output.";

 
 // The setiosflags will set printing in fixed format
 // the setiosflags applies to all printing until reset

 foutput << " The Vertices for the Cubic Bezier Curve are: \n\n " \
      << setiosflags(ios::fixed)  << endl;
 foutput << setprecision(3) << setw(8) << x1  \

  // another way to set width and precision
  // must be repeated for each time a variable is printed

      << setprecision(3) << setw(8) << y1 << endl;
 foutput << setprecision(3) << setw(8) << x2  \
      << setprecision(3) << setw(8) << y2 << endl;
 foutput << setprecision(3) << setw(8) << x3  \
      << setprecision(3) << setw(8) << y3 << endl;
 foutput << setprecision(3) << setw(8) << x4  \
      << setprecision(3) << setw(8) << y4 << endl;
 
 

 finput.close();
 foutput.close();

 // must close all open files before exiting

 return(0);
}
 

The output file look as follows:

 The Vertices for the Cubic Bezier Curve are:

 
   0.000   0.200
   0.300   0.556
   0.500   0.778
   1.000   0.900

 Program Control

The statements used to control program flow are very similar to those you have seen in VB, Matlab and Java.  You would also have figured out by now that C++ uses the semicolon as the statement terminator.   Blocks of statement are enclosed in curly brackets.  Since we have used these statements before in other languages we forsake the examples.
 

If

The general form of if statement is

        if    (expression)
            statement;

        if     (expression)        // note that we are borrowing style from Java
        {    statement1;
             statement2;
                ---------
             last statement;
        }                                // note that a closing brace is not
                                         // followed with a semicolon

        if - else

         if     (expression)
        {    statement set 1;
        }
        else
        {    statement set 2;
        }

if  -  else  -  if

if    (expression 1)
{    statement set 1;
}    else if     (expression 2)
{    statement set 2;
}    else
{    default action;
}

?    :    ternary operator

test_expression    ?  true_action  :  false_action;

Since we are building only cubic curves, and we allow any value of order to be inputted, we can control the action by

order = (order > 3)  ? (order = 3)  :  (order = 3);

Note , you can achieve the same using an if - else statement.

Switch Case

switch   (expression - must yield an  integer)
{    case constant 1:
        statement set 1;            // don't forget the blocks for more than one statement
        break;

    case constant 2:
        statement set 2;
        break;

    default:
        statements;
}

The switch statement in C++ is accompanied by the following  list of warnings:

all case labels must be unique
a default label is not rquired
the break statement is necessary to exit the switch statement after a case
the break is not needed when falling off the end
case and default keyword combination cannot occur outside the switch
a switch cannot bypass initialization of a variable unless the entire scope of the variable is bypassed
 

Loops

C++ has forwhile ,  and do loops.   The for loop is used when the number of repetitions are known.  The while and do are useful when this is not known.

for

The syntax for a for loop:
 
for    ( initial_expression;  terminate_condition ; increment_expression)
{    statements;
}

while

The syntax for the while loop.  Here the statements are executed zero or more times

while  (expression)
{    statements;
}

do - while

The syntax for the do statement

do
{    statements;
}    while    (expression);

Here the statements are executed one or more times.  Note the semicolon after while.

Interrupting normal control flow

break

We have seen the break in switch case statement.  The break statement can be used to exit the loop statements prematurely.

for ( i = 0; i < 10; ++i)
{    cin >> x;
    if ( x < 0.0 )
    {    cout << " Thats it - who asked you to enter a negative number"  << endl;
        break;            // exit the loop
    }
    cout << sqrt(x)  << endl;
}

//  break jumps till here - Note: break applies to for
//  and not the if statement
// hacked from Pohl

continue

for (i = 0; i < 10; i++)
{   cin.get(c);     // reads a charcter
    if (isdigit(c))
        continue;   // continue suspends the current loop
                    // iteration and begins the next one

    ...............// other processing
 

// continue jumps here
}

goto    label

The use of this statement is usually discouraged.  It forces the program to break off and start executing from a label indentified in the code.

goto    label;

if (order > 3)
    goto error;
else
    read_Vertex(order):

    ............................
error:    cerr << " ERROR: order of curve is not three" << endl;
 

return( value)

The return is normally used to exit main or functions.  

Arrays

Like Java C++ allows you arrays  of anything.  All elements must be of the same type.  The starting subscri

Today, there have been 5 visitors (7 hits) on this page!
This website was created for free with Own-Free-Website.com. Would you also like to have your own website?
Sign up for free