Friday, June 12, 2009

VISUAL C++

Microsoft Visual C++ (often abbreviated as MSVC) is a commercial integrated development environment (IDE) product engineered by Microsoft for the C, C++, and C++/CLI programming languages. It has tools for developing and debugging C++ code, especially code written for the Microsoft Windows API, the DirectX API, and the Microsoft .NET Framework.

The predecessor to Visual C++ was called Microsoft C/C++. There was also a Microsoft QuickC 2.5 and a Microsoft QuickC for Windows 1.0.

Visual C++ 1.0, which included MFC 2.0, was the first version of Visual C++, released in 1992, available in both 16-bit and 32-bit versions.
Visual C++ 1.5, which included MFC 2.5, added OLE 2.0 and ODBC support to MFC. It was 16-bit only and was the first version of Visual C++ that came only on CD-ROM.
Visual C++ 1.52c was a patched version of 1.5, but deserves its own entry since it is the last, and arguably most popular, development platform for Microsoft Windows 3.x. It is available through Microsoft Developer Network.
Visual C++ 2.0, which included MFC 3.0, was the first version to be 32-bit only. In many ways, this version was ahead of its time because Windows 95, then codenamed "Chicago", was not released, and Windows NT had only a small market share. As a result, this release was almost a "lost generation". Updates available through subscription included version 2.1 and 2.2. Microsoft included and updated Visual C++ 1.5 as part of the 2.x releases up to 2.1, which included Visual C++ 1.52, and both 16-bit and 32-bit version of the Control Development Kit (CDK) were included. Visual C++ 2.x also supported Win32s development. It is available through Microsoft Developer Network. There was a Visual C++ 2.0 RISC Edition for MIPS and Alpha processors, as well as a cross-platform edition for the Macintosh (68000 instruction set).
Visual C++ 4.0, which included MFC 4.0, was designed for Windows 95 and Windows NT. To allow support of legacy (Windows 3.x/DOS) projects, 4.0 came bundled with the Visual C++ 1.52 installation CD. Updates available through subscription included Visual C++ 4.1, which came with the Microsoft Game SDK (later released separately as the DirectX SDK), and Visual C++ 4.2. 4.2 did not support Windows 3.x (Win32s) development. This was the final version with a cross-platform edition for the Macintosh available and it differed from the 2.x version in that it also allowed compilation for the PowerPC instruction set.
Visual C++ 5.0, which included MFC 4.21, was a major upgrade from 4.2.
Visual C++ 6.0 (commonly known as VC6), which included MFC 6.0, was released in 1998. The release was somewhat controversial since it did not include an expected update to MFC. Visual C++ 6.0 is still quite popular and often used to maintain legacy projects. There are however issues with this version under Windows XP, especially under the debugging mode (ex: the values of static variables do not display). The debugging issues can be solved with a patch called the "Visual C++ 6.0 Processor Pack" downloadable from http://msdn2.microsoft.com/en-us/vstudio/aa718349.aspx; This page stresses that Users must also be running Windows 98, Windows NT 4.0, or Windows 2000.'
Visual C++ .NET 2002 (known also as Visual C++ 7.0), which included MFC 7.0, was released in 2002 with support for link time code generation and debugging runtime checks, .NET 1.0 and Visual C# and Managed C++. The new user interface used many of the hot keys and conventions of Visual Basic, which accounted for some of its unpopularity among C++ developers.
Visual C++ .NET 2003 (known also as Visual C++ 7.1), which included MFC 7.1, was released in 2003 along with.NET 1.1 and was a major upgrade to Visual C++ .NET 2002. It was considered a patch to Visual C++ .NET 2002. Accordingly, the English language upgrade version of Visual Studio .NET 2003 shipped for minimal cost to owners of the English language version of Visual Studio .NET 2002. This is the last version to support Windows 95 as a target.
eMbedded Visual C++ in various versions was used to develop for some versions of the Windows CE operating system. Initially it replaced a development environment consisting of tools added onto Visual C++ 6.0. eMbedded Visual C++ was replaced as a separate development environment by Microsoft Visual Studio 2005.
Visual C++ 2005 (known also as Visual C++ 8.0), which included MFC 8.0, was released in November 2005. This version supports .NET 2.0 and dropped Managed C++ for C++/CLI. It also introduced OpenMP. With Visual C++ 2005, Microsoft also introduced Team Foundation Server. Visual C++ 8.0 has problems compiling MFC AppWizard projects that were created using Visual Studio 6.0, so maintenance of legacy projects can be continued with the original IDE if rewriting was not feasible.
Visual C++ 2008 (known also as Visual C++ 9.0) was released in November 2007. This version supports .NET 3.5, and it is currently the latest stable release. By default, all applications compiled against the Visual C++ 2008 Runtimes (static and dynamic linking) will only work under Windows 2000 and later.[1]
Visual C++ 2010 (known also as Visual C++ 10.0) will be released in the 2009-2010 timeframe. It is currently in development, and available only in the form of a Community Technology Preview. The Visual C++ team is considering using a SQL Server Compact database to store information about the source code, including IntelliSense information, for better IntelliSense and code-completion support.[2] This version adds a modern C++ parallel computing library called the Parallel Patterns Library, partial support for C++0x, and significantly improved IntelliSense. This version is built around .NET 4.0, but still supports compiling to Machine Code.

Current editions
There are four current versions of Visual C++ available:

Microsoft Visual C++ 2008 Express Edition
Microsoft Visual Studio 2008 Standard
Microsoft Visual Studio 2008 Professional
Microsoft Visual Studio 2008 Team System


Visual C++ is included in Visual Studio.

Microsoft Visual C++ 2008 Express is available as a free download at the MSDN site.

Microsoft Visual C++ 2005 Express is available as a free download at the MSDN site under "Previous Version".


Visual C++ 2008 Express
This Microsoft Visual C++ (or Visual C++ 9.0) is available in two flavors: as a part of Microsoft Visual Studio and as a standalone "Express Edition" product. Both should be available for MSDN subscribers and were released officially in November of 2007.

Microsoft Visual C++ 2008 Express Edition is available from the Microsoft Developer Network (MSDN) web site as a free download.

Tuesday, June 9, 2009

Dev C++

Dev-C++ is a free integrated development environment (IDE) distributed under the GNU General Public License for programming in C/C++. It is bundled with MinGW, a free compiler. The IDE is written in Delphi.

The project is hosted by SourceForge. Dev-C++ was originally developed by programmer Colin Laplace. Dev-C++ runs exclusively on Microsoft Windows.

Bloodshed Dev-C++ is a full-featured Integrated Development Environment (IDE) for the C/C++ programming language. It uses the MinGW port of the GCC (GNU Compiler Collection) as its compiler. Dev-C++ can also be used in combination with Cygwin or any other GCC-based compiler.[1]

The program itself has a look-and-feel similar to that of the more widely-used Microsoft Visual Studio. One additional aspect of Dev-C++ is its use of DevPaks, packaged extensions on the programming environment with additional libraries, templates, and utilities. DevPaks often contain, but are not limited to, GUI utilities, including popular toolkits such as GTK+, wxWidgets, and FLTK. Other DevPaks include libraries for more advanced function use.

Dev-C++ is generally considered a Windows-only program. There is also a Linux version available, but it is in alpha and has not been updated since July 2002.

Devpaks
Devpaks.org is a site from which users of Dev-C++ can download additional libraries, or packages of code that increase the scope and functionality of Dev-C++, such as graphics, compression, animation, sound support and many more. On the site, Devpaks are defined as "Libraries (especially open source libraries) are typically distributed as sources. This is convenient, but it can be difficult or time consuming to compile such a library. So the creators of Dev-C++ introduced devpak -- development package, which contains precompiled version of a library, so even a beginner can use them. Dev-C++ also includes several tools for downloading, installing and creating packages." Users can create Devpaks and host them free on the site. Also, they are not limited to use with Dev C++. The site says "A typical devpak will work with any MinGW distribution (with any IDE for MinGW). Simply rename the file from something.devpak to something.tar.bz2 and open it with an archiver (e.g. 7-zip). You will see one file with some meta information (name, version, author etc.) and a directory. Simply unpack the contents of the directory to your MinGW directory tree. The Code::Blocks IDE has plugin for installing and manipulating devpaks." (All quotes from this paragraph are quoted from Devpaks.org)


Development status
The project is no longer noticeably active, with no news posted nor any updated versions released since February 22, 2005. However there is a development team that has taken the Dev-C++ IDE and added new features such as support for multiple compilers and a RAD designer for wxWidgets applications. This IDE can be found under the name wxDev-C++.

Turbo c++

Turbo C++ is a C++ compiler and integrated development environment (IDE) originally from Borland. It is currently distributed by Embarcadero Technologies, which acquired all of Borland's compiler tools with the purchase of its CodeGear division in 2008. The original Turbo C++ product line was put on hold after 1994, and was revived in 2006 as an introductory-level IDE, essentially a stripped-down version of their flagship C++ Builder. Turbo C++ 2006 was released on September 5, 2006 and is available in 'Explorer' and 'Professional' editions. The Explorer edition is free to download and distribute while the Professional edition is a commercial product. The professional edition is no longer available for purchase from Borland.

Historical versions
The first release of Turbo C++ was made available during the MS-DOS reign on personal computers. It came up in versions 1.0, running on OS/2 and version 1.01, released on February 28, 1991 [1], running on MS-DOS. The latter was able to generate both COM and EXE programs, and was shipped with Borland's Turbo Assembler compiler for Intel x86 processors. The initial version of the Turbo C++ compiler was based on a front end developed by TauMetric (TauMetric was later acquired by Sun Microsystems and their front end was incorporated in Sun C++ 4.0, which shipped in 1994).This compiler supported the AT&T 2.0 release of C++.

Turbo C++ 3.0 was released in 1991 (shipping on November 20), and came in amidst expectations of the coming release of Turbo C++ for Microsoft Windows. Initially released as an MS-DOS compiler, 3.0 supported C++ templates, Borland's inline assembler, and generation of MS-DOS mode executables for both 8086 real-mode & 286-protected (as well as the Intel 80186.) 3.0's implemented AT&T C++ 2.1, the most recent at the time. The separate Turbo Assembler product was no longer included, but the inline-assembler could stand in as a reduced functionality version.

Soon after the release of Windows 3.0, Borland updated Turbo C++ to support Windows application development. The Turbo C++ 3.0 for Windows product was quickly followed by Turbo C++ 3.1 (and then Turbo C++ 4.5). It's possible that the jump from version 1.x to version 3.x was in part an attempt to link Turbo C++ release numbers with Microsoft Windows versions; however, it seems more likely that this jump was simply to synchronize Turbo C and Turbo C++, since Turbo C 2.0 (1989) and Turbo C++ 1.0 (1990) had come out roughly at the same time, and the next generation 3.0 was a merger of both the C and C++ compiler.

Starting with version 3.0, Borland segmented their C++ compiler into two distinct product-lines: "Turbo C++" and "Borland C++". Turbo C++ was marketed toward the hobbyist and entry-level compiler market, while Borland C++ targeted the professional application development market. Borland C++ included additional tools, compiler code-optimization, and documentation to address the needs of commercial developers. Turbo C++ 3.0 could be upgraded with separate add-ons, such as Turbo Assembler and Turbovision 1.0.

Version 4.0 was released in November 1993 and was notable (among other things) for its robust support of templates. In particular, Borland C++ 4 was instrumental in the development of the Standard Template Library, expression templates, and the first advanced applications of template metaprogramming. With the success of the Pascal-evolved product "Delphi", Borland ceased work on their Borland C++ suite and concentrated on C++ Builder for Windows. C++ Builder shared Delphi's front-end application framework, but retained the Borland C++ back-end compiler. Active development on Borland C++/Turbo C++ was suspended until 2006 (see below.)


Legacy software
Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from Borland's Antique Software website.
Turbo C++ 3.0 (DOS) was included in the Turbo C++ Suite 1.0, which is no longer sold by Borland. Turbo C++ 3.0 (DOS) can be downloaded from http://vetusware.com.

Friday, June 5, 2009

File Handling

C++ provides the following classes to perform output and input of characters to/from files:

ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.


These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:

// basic file operations
#include
#include
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}


OUTPUT:
[file example.txt]
Writing this to a file



This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.

But let's go step by step:


Open a file


The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.

In order to open a file with a stream object we use its member function open():

open (filename, mode);


Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);


Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:

class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out



For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.

File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).

Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing:

ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);


Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.

To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with output */ }



Closing a file
When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

myfile.close();


Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.

In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close().


Text files
Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

Data output operations on text files are performed in the same way we operated with cout:

// writing on a text file
#include
#include
using namespace std;

int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
[file example.txt]

OUTPUT:
This is a line.
This is another line.


Data input from a file can also be performed in the same way that we did with cin:

// reading a text file
#include
#include
#include
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}


OUTPUT:
This is a line.
This is another line.


This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called eof() that returns true in the case that the end of the file has been reached. We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the file has been reached).

Thursday, June 4, 2009

Dynamic Memory Allocation

Consider a array declaration

int marks[100];
Such a declaration would typically be used if 100 student's marks were to be stored in memory. The moment we make this declaration 200 bytes are reserved in the memory for storing 100 integers in it. However it mayso happen that when we actally run the program, we might be interested in storing only 60 students marks.Even in this case 200 bytes would get reserved in the memory, which would result in wastage of memory.

Other way round there always exist a possibility that when you run the program you need to store more than 100 students marks. In this case the array would fall short in size. Moreover there is no way to increase or decrease the array size during execution of the program. In other words,when we use array, static memory allocation takes place. What if we want to allocate memory only at the time of execution? This is dome using standard library functions malloc() and calloc(). Since these functions allocate memory on the fly(during execution) they are often known as 'dynamic memory allocation functions'. Let us now see a program, which uses the concept of dynamic memory allocation.

#include
main()
{
int n,avg,i,*p,sum=0;

cout<<"Enter the number of students";
cin>>n;
p=(int *)malloc(n*2);
if(p==NULL)
{cout<<"memory allocation unsuccessful";
exit();
}
for(i=0;icout<for(i=0;isum=sum+*(p+i);
avg=sum/n;
cout<<"average marks"<}


Here we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as it is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc().malloc() returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p. Since malloc() returns a void pointer we have typecasted it into a integer pointer. In the first for loop using simple pointer arithmatic we have stored the marks entered form the keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks

The calloc()function works exactly similar to malloc() except for the fact that it needs two arguments. for example,

int *p;
p=(int*)calloc(10,2);


Here 2 indicates that we wish to allocate memory for storing integers,(since an integer takes 2 bytes entity) and 10 indicates that we want to reserve space for storing 10 integers. Another minor difference between malloc() and calloc() is that, by default, the memory allocated by malloc() contains garbage values, whereas that allocated by calloc() contains all zeros. While using these functins it is necessary to include the file at the beginning of the program.


Sunday, May 31, 2009

Introduction To Pointers in C++

Pointers Fundamentals


Introduction


When writing a program, you declare the necessary variables that you will need in order to accomplish your work. When declaring variables, you are simply asking the computer
to reserve a set amount of space in its memory for a particular object you want to use. When you declare a variable, the computer reserves an amount of space for that variable, and uses the variable's name to refer to that memory space. This will allow you to store something, namely the value of that variable, in that space. Indeed, the computer refers to that space using an address. Therefore, everything you declare has an address, just like the address of your house. You can find out what address a particular variable is using.


A Review of References and Functions

Here are a few things you know already about writing a program:

To use a variable, you declare it first to tell the compiler what kind of variable you are planning to use and what its name is .

Once you declare a variable, the compiler reserves and assigns it a portion of space in memory and locates it there so that whenever you need that variable, you just call it and then use it.

To use a function, you have to define it, tell the compiler what the function is supposed to do, and whether the function is supposed to give back a result or not, after it has performed its assignment.

To see a variable's address, you can use the & operator followed by the name of the variable. For example, after declaring an integer as

int numberOfStudents;


you can find the address where the NumberOfStudents variable is located by using:

cout << &numberOfStudents;

This program would give you the address of the declared variable:

#include
using namespace std;

int main()
{
int value;

cout << "Value lives at "
<< &value;

cout << "\n\n";
return 0;
}


After executing the program, you could get:

Value lives at: 0x0065FDF4



Using Pointers



Why Use Pointers?


Every time you declare a variable, the compiler puts it somewhere, which you can now refer to as an address. Once you know that address, you can use it.

Like a reference, when you pass an argument to a function, the argument is passed using its address. This allows the calling function to dig into the address of the variable (the argument) and use the value directly. This transaction, like that of passing an argument by reference, allows the calling function to alter the real value of the argument. Using this ability, a pointer can allow you to return many values from a function; as opposed to a regular argument passing where the data, although changed inside of the calling function, will regain its previous value once the calling function is exited. Therefore, passing arguments as pointers allows a function to return many values, even if a function is declared as void.

When you declare an array, you must specify the dimension of the array. That's already a problem: what if you don't know and don't want to know the dimension of the array? Pointers provide an ability that regular arrays do not have. Since pointers have a different and better system of managing memory, a pointer can store an array of almost any size; this is tremendous when dealing with arrays of characters or a whole text. Using this feature, when declaring a pointer in replacement of an array, you do not have to worry about the size of the array, the compiler will take care of that. Again, this feature allows you to pass pointers to a function (just like arrays) and return a value that has been altered even if the function is declared as void. This is even more dynamic with multidimensional arrays.


Definition


Pointers are not particularly useful when declared and used inside of one function. They show their capabilities when different functions (and/or objects) exchange data stored in those pointers.

As you can see from the execution of the program above, the address of a variable is very difficult to read and interpret. Fortunately, we don't need to know that address and we don't need to know what it means or where the variable is located. C++ provides an alternative to this problem.

Instead of referring to a variable's address directly, you are allowed to declare another variable, and then use that new variable to refer to the address of the variable you are interested in. A pointer is a variable that refers to another variable's address.

Just like any variable in C++, you should declare and initialize a pointer variable before using it. To declare a pointer variable, use an identifier, followed by an asterisk (*), followed by the name of the pointer, and a semi-colon. Here is the formula:

DataType * PointerName;


The identifier should be one of those we have learned already. This means it could be an int, a char, a double, etc. The identifier should be the same type of identifier the pointer variable will point to. Therefore, if you are declaring a pointer that will point to an integer variable, the pointer identifier should be an integer.

The asterisk (*) lets the compiler know that the variable that follows is a pointer. There are three ways you can type the asterisk. These are

DataType* PointerName;
DataType * PointerName;
DataType *pointerName;


By default, it does not matter how you append the *, the compiler will know that the thing that follows is a variable.

Be careful when declaring various pointers. If you declare a few of them on the same line, like this:

DataType* pointer1, pointer2;

Only the first variable is a pointer, the second is a regular variable. If you want to declare different variables, you use:

DataType* pointer1, *pointer2;

Or

DataType* pointer1;
DataType* pointer2;


Since the name of the pointer is indeed the name of a variable, you will follow the naming rules that govern every C++ variable.

#include
using namespace std;

int main()
{
int value;
int *pointer;

cout << "Value lives at " << &value << "\n";
cout << "Pointer lives at " << &pointer;

cout << "\n\n";
return 0;
}


After executing the program, you might get:

Value lives at: 0x0065FDF4
Pointer lives at: 0x0065FDF0



Initializing a Pointer


One of the reasons you are using a pointer is to find an alternative to knowing the address of a variable. Therefore, from now on, we are not interested in a variable's real address. Instead, we will use a pointer to point to that variable.

As we have learned already, a variable should be initialized before being used. This allows the compiler to put something into the memory space allocated for that variable.

To use a pointer P effectively, for its intended purpose, you need to tell the compiler that: pointer P will be used to point to the address of variable V. You do this by initializing the pointer. A pointer is initialized (almost) like any other variable, using the assignment operator (=).

There are two main ways you can initialize a pointer. When declaring a pointer like this:

int* Pointer;

initialize it by following the assignment operator with & operator and the name of the variable, like this

int* Pointer = &Variable;

You can also initialize a pointer on a different line, after declaring it. This time, you should not use the asterisk on the Pointer, but the compiler should know that the pointer will point to a variable's address; therefore, the name of the variable will still use the &.


#include
using namespace std;

int main()
{
int value = 12;
int *pointer = &value;

cout << "Value lives at: " << value << "\n";
cout << "Pointer lives at: " << *pointer;
cout << "\n\n";
return 0;
}


The program would produce:

Value lives at: 12
Pointer lives at: 12


This program could also have the pointer initialized as:

#include
using namespace std;

int main()
{
int Value = 12;
int *pointer;

cout << "Value lives at: " << value << "\n";

Pointer = &value;
cout << "Pointer lives at: " << *pointer;
cout << "\n\n";
return 0;
}


And it would produce the same result. As another of the program, you can first declare both variables, then initialize them later on, when needed:

#include
using namespace std;

int main()
{
int value;
int *pointer;

pointer = &value;
Value = 26;
cout << "Value = " << value << "\n";
cout << "*Pointer = " << *pointer << "\n";

cout << "\n";
return 0;

}

Once you have declare a variable and assign it to a pointer, during the course of your program, the value of a variable is likely to change, you can therefore assign it a different value:

#include
using namespace std;

int main()
{
int value;
int *pointer;

Pointer = &value;
Value = 26;
cout << "Value = " << value << "\n";
cout << "*pointer = " << *pointer << "\n";

Value = 35;
cout << "Value = " << value << "\n";
cout << "*pointer = " << *pointer << "\n";


cout << "\n";
return 0;
}


As you know now, both *pointer and Value have the same value. This allows you to change the value of the pointer directly and affect the main variable meanwhile. Therefore, you can safely change the value of the pointer and it will be assigned accordingly. To see an example, make the following change to the file:

#include
using namespace std;

int main()
{
int value;
int *pointer;

Pointer = &value;
Value = 26;
cout << "Value = " << value << "\n";
cout << "*pointer = " << *pointer << "\n";

Value = 35;

cout << "Value = " << value << "\n";
cout << "*pointer = " << *pointer << "\n";

*pointer = 144;
cout << "Value = " << value << "\n";
cout << "*pointer = " << *pointer << "\n";

cout << "\n";
return 0;
}


This would produce:

Value = 26
*pointer = 26
Value = 35
*pointer = 35
Value = 144
*pointer = 144



A Pointer to a Pointer


Instead of pointing to a regular variable, a pointer can be made to point to another pointer. To apply this, always remember that you must specify what target a pointer is pointing to. Once again, consider the following example:

#include
using namespace std;

int main()
{
int value = 26;
int *pointer;

pointer = &value;

cout << " Value = " << value << "\n";
cout << "*Pointer = " << *pointer << "\n";

return 0;
}


This would produce:

Value = 26
*Pointer = 26

In this program, if necessary, you can declare a new variable that is a pointer that itself points to another pointer. When declaring such a variable, precede it with two *. After declaring the pointer, before using it, you must initialize it with a reference to a pointer, that is, a reference to a variable that was declared as a pointer. Here is an example:

#include
using namespace std;

int main()
{
int value = 26;
int *pointer;
int **pointerToPointer;

pointer = &value;
pointerToPointer = &pointer;

cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

return 0;
}


This would produce:

Value = 26
*Pointer = 26
**Pointer = 26


Just as demonstrated earlier, after initializing a pointer, if you change the value of the variable it points to, the pointer would be updated. Consider the following program:

#include
using namespace std;

int main()
{
int value = 26;
int *pointer;
int **pointerToPointer;

pointer = &value;
pointerToPointer = &pointer;

cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

value = 4805;

cout << "After changing the value of the main variable...\n";
cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

return 0;
}


This would produce:

Value = 26
*Pointer = 26
**Pointer = 26
After changing the value of the main variable...
Value = 4805
*Pointer = 4805
**Pointer = 4805

Notice that, by changing the value of the original variable, when accessing its pointer or the pointer to its pointer, they reflect the new value. In the same way, instead of (directly) changing the value of the variable, you can change the value of its pointer. You can also change the value of the pointer to its pointer. Like a chain reaction, all variables would be updated. Consider the following program:

#include
using namespace std;

int main()
{
int value = 26;
int *pointer;
int **pointerToPointer;

pointer = &value;
pointerToPointer = &pointer;


cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

value = 4805;

cout << "\nAfter changing the value of the main variable...\n";
cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

*pointer = -728;

cout << "\nAfter changing the value of the pointer...\n";
cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

**pointerToPointer = 945580;

cout << "\nAfter changing the value of the pointer to pointer...\n";
cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";

return 0;
}


This would produce:

Value = 26
*Pointer = 26
**Pointer = 26

After changing the value of the main variable...
Value = 4805
*Pointer = 4805
**Pointer = 4805

After changing the value of the pointer...
Value = -728
*Pointer = -728
**Pointer = -728

After changing the value of the pointer to pointer...
Value = 945580
*Pointer = 945580
**Pointer = 945580



Operations on Pointers


Introduction


Consider that, added just a few rules, a pointer is a variable like any other: it can get its value from the user (indirectly), you can apply any of the algebraic operations we have learned, it can be incremented, it can be applied on a function, etc.

A variable is a value that is supposed to change some time to time. Since a pointer is a variable whose value points to another variable, the value of a pointer is affected by the variable it points to. You can use this indirection to change the value of a pointer when changing its main variable.

To get a value from the user, we have already learned that you can use the cin operator. When using a pointer to get a value from the user, don't forget the * operator, otherwise, the compiler would get confused.

We have already learned how to request and display the value of a regular variable from the user:

#include
using namespace std;

int main()
{
int students;

cout << "Number of students: ";
cin >> students;

cout << "\nNumber of students: " << students;

cout << "\n\n";
return 0;
}


Once you have gotten a value and store it in a variable, it is available:

#include
using namespace std;

int main()
{
int students;
int *ptrStudents;

ptrStudents = &students;
cout << "Number of students: ";
cin >> students;
cout << "\nNumber of students: " << students
<< "\nThat is: " << *ptrStudents << " students.";
cout << "\n\n";
return 0;

}

This could produce:

Number of students: 24

Number of students: 24
That is: 24 students


In the same way, you can request a value from the user and store it in the pointer. To see an example, make the following change to the file:

#include
using namespace std;

int main()
{
int students;
int *ptrStudents;

ptrStudents = &students;
cout << "Number of students: ";
cin >> *ptrStudents;

cout << "\nNumber of students: " << students
<< "\nThat is: " << *ptrStudents << " students.";

cout << "\n\n
";
return 0;
}


Of course, you can use various pointers on the same program. Apply an example by making the following changes:

#include
using namespace std;

int main()
{
int boys;
int girls;
int *ptrBoys;
int *ptrGirls;

ptrBoys = &boys;
ptrGirls = &girls;

cout << "Number of male students: ";
cin >> *ptrboys;

cout << "Number of female students: ";
cin >> *ptrGirls;
cout << "\nNumber of students:";

cout << "\nBoys:" << "\t" << Boys
<< "\nThat is: " << *ptrBoys << " students.";
cout << "\nGirls:" << "\t" << Girls
<< "\nThat is: " << *ptrGirls << " students.";

cout << "\n\n";
return 0;
}


We have learned how to perform algebraic calculations and expressions in C++. When performing these operations on pointers, remember to use the * for each pointer involved. The calculations should be as smooth:

#include
using namespace std;

int main()
{
int boys;
int girls;
int total;
int *ptrBoys;
int *ptrGirls;
int *ptrTotal;


ptrBoys = &boys;
ptrGirls = &girls;
ptrTotal = &total;

cout << "Number of male students: ";
cin >> *ptrBoys;
cout << "Number of female students: ";
cin >> *ptrGirls;

cout << "\nNumber of students:";
cout << "\nBoys:" << "\t" << Boys
<< "\nThat is: " << *ptrBoys << " students.";
cout << "\nGirls:" << "\t" << Girls
<< "\nThat is: " << *ptrGirls << " students.";


Total = Boys + Girls;

*ptrTotal = *ptrBoys + *ptrGirls;

cout << "\n\nTotal number of students: " << total;
cout << "\nThere are " << *ptrTotal << " students";

cout << "\n\n";
return 0;
}


This would produce:

Number of male students: 26
Number of female students: 24

Boys: 26
That is: 26 students
Girls: 24
That is: 24 students

Total number of students: 50
There are 50 students




Passing Pointers to Functions

We know that a function uses arguments in order to carry its assignment. The arguments are usually provided to the function. When necessary, a function also declares its own variable to get the desired return value. Like other variables, pointers can be provided to a function, with just a few rules.

When declaring a function that takes a pointer as an argument, make sure you use the asterisk for the argument or for each argument. When calling the function, use the references to the variables. The function will perform its assignment on the referenced variable(s). After the function has performed its assignment, the changed value(s) of the argument(s) will be preserved and given to the calling function.

Here is a starting file from what we have learned so far:

#include
using namespace std;

int main()
{
int shirts = 12;
int pants = 5;

cout << "Shirts = " << shirts << endl;
cout << "Pants = " << pants << endl;

cout << endl;
return 0;
}


This would produce:

Shirts = 12
Pants = 5



To pass arguments to a function, you can make the following changes:

#include
using namespace std;

int main()
{
int shirts = 3;
int pants = 5;
void Deposit(int s, int p);

cout << "When starting, within main():\n";
cout << "\tShirts = " << shirts << endl;
cout << "\tPants = " << pants << endl;

Deposit(Shirts, Pants);

cout << "\n\nAfter calling Deposit(), within main():\n";
cout << "\tShirts = " << shirts << endl;

cout << "\tPants = " << pants << endl;
cout << endl;
return 0;
}


void Deposit(int s, int p)
{
s = 8;
p = 12;

cout << "Within Deposit()"
<< "\n\tShirts = " << s
<< "\n\tPants = " << p;
}


After executing, the program would produce:

When starting, within main():
Shirts = 3
Pants = 5
Within Deposit()
Shirts = 8
Pants = 12
After calling Deposit(), Within main():
Shirts = 3
Pants = 5

To pass pointer arguments, use the asterisks when declaring the function, and use the ampersand & when calling the function. Here is an example:

#include
using namespace std;

int main()
{
int shirts = 12;
int pants = 5;
void Deposit(int s, int p);
void Pickup(int *sht, int *pt);

cout << "When starting, within main():\n";
cout << "\tShirts = " << shirts << endl;
cout << "\tPants = " << pants << endl;

Deposit(shirts, pants);
cout << "\n\nAfter calling Deposit(), within main():\n";
cout << "\tShirts = " << shirts << endl;
cout << "\tPants = " << pants << endl;

Pickup(&shirts, &pants);
cout << "\n\nAfter calling Pickup(), within main():\n";
cout << "\tShirts = " << shirts << endl;
cout << "\tPants = " << pants << endl;

cout << endl;
return 0;
}

void Deposit(int s, int p)
{
s = 8; p = 5;

cout << "\nWithin Deposit()"
<< "\n\tShirts = " << s
<< "\n\tPants = " << p;
}

void Pickup(int *sht, int *pt)
{
*sht = 26;

*pt = 17;

cout << "\nWithin Pickup()"
<< "\n\tShirts = " << *sht
<< "\n\tPants = " << *pt;
}


The result of executing the program is:

When starting, within main():
Shirts = 12
Pants = 5

Within Deposit()
Shirts = 8
Pants = 5

After calling Deposit(), within main():
Shirts = 12
Pants = 5

Within Pickup()
Shirts = 26
Pants = 17

After calling Pickup(), within main():
Shirts = 26
Pants = 17



A Function That Returns a Pointer


If you want a function to return a pointer, when declaring the function, make sure that you specify its return type as a pointer and you can use a type of your choice. Here is an example of such a declaration:

#include
using namespace std;

int main()
{
int *GetNumber();

return 0;
}


In this case, we have declared a function named GetNumber that will return a pointer to int. When implementing the function, you can apply any of the techniques we have used so far inside the function. The most important rule to keep in mind is that the function must return a pointer and not a regular value. In the same way, when calling a function that returns a pointer, you can use its value only where the returned pointer is appropriate. For example, you can assign its returned value only to a pointer of the same type. Here is an example:

#include
using namespace std;

int main()
{
int *GetNumber();
int *number;

number = GetNumber();

cout << "Number = " << *number << endl;
return 0;
}

int *GetNumber()
{
int *a = new int(2885);

return a;
}

This would produce:

Number = 2885




Pointers and Memory Management


By definition, the variables in your program are meant to "vary", that is, their values change regularly. When you declare a variable, such as

int Shirts;

the compiler reserves an appropriate amount of memory space for that particular variable. This is done when the program is compiling but before its execution. This means of providing memory space is called static allocation, the memory space is "allocated" to that variable. When the program executes, this static memory allocation does not change; but the memory space might be empty, especially if the variable is not initialized. This is important: the fact that a variable is not initialized means its memory space is empty, it is not equal to zero; it is simply empty. Nothing is occupying it.

You can also ask the compiler to provide memory when the program is executing. This is called dynamic allocation. Dynamic allocation is performed using the new operator like this:

PointerName = new DataType;


The keyword new is required. The data type can be any of those we are already familiar with, but it must be appropriate to the variable it is pointing to. This means that, if it is pointing to an integer variable, the data type must be an integer. For example, our corresponding dynamic allocation would be:

ptrShirts = new int;

After dynamically allocating memory, you can assign a new value to the pointer for any purpose. Once the memory is not anymore in use, you should reclaim it. This is done with the delete keyword, like this:

delete ptrShirts;

Here is a starting point for this section
:

#include
using namespace std;

int main()
{
int studentAge = 12;


cout << "Student age = " << studentAge << endl;

cout << endl;
return 0;
}


Now, let's add a pointer and try to access it without initializing it:

#include
using namespace std;

int main()
{
int studentAge = 12;
int* age;

cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

cout << endl;
return 0;
}


You will get a value that is not insignificant. Depending on the compiler, you might even get a nasty dialog box and a warning. This is because you were trying to access a pointer that has not been initialized.

You can initialize the pointer like this:

#include
using namespace std;

int main()
{
int studentAge = 12;
int* age;

Age = &studentAge;

cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

cout << endl;
return 0;
}


To illustrate that an un-initialized variable has an address (although empty), you can change the file as follows:



When you initialize a variable, its value gets stored in the memory space that was statically allocated by the compiler. In the same way, since its corresponding pointer points to its address, you can initialize the pointer and still access the value assigned to the variable it is pointing to. To see an example of a pointer, and not the variable itself being initialized, make the following changes to the file:

#include
using namespace std;

int main()
{
int studentAge;
int *age;

age = &studentAge;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

*Age = 15;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;
cout << "\n";
return 0;
}

This results in:

Student age = -858993460
*Age = -858993460
Student age = 15
*Age = 15

To dynamically allocate memory, you assign the pointer with the new keyword followed by the appropriate identifier:

#include
using namespace std;

int main()
{
int studentAge;
int *age;

age = &studentAge;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

*age = 15;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

age = new int;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;
cout << "\n";
return 0;
}

As you can see, since the value of the pointer has been dynamically assigned, its address is now empty. If you want to access its content, you have to reassign it another value; this is one of the mistakes that happen regularly in a program. When this happens, the program will compile fine, without any error or warning, but the result… Therefore, you should always know the value of a pointer. In our example, you can reassign a value to the empty pointer:

age = new int;
*Age = 17;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;
cout << "\n";
}

After using a pointer, don't forget to clean your memory. You do this using the delete operator:

#include

int main()
{
int studentAge;
int *age;

age = &studentAge;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

*age = 15;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

Age = new int;
*age = 17;
cout << "Student age = " << studentAge << endl;
cout << "*Age = " << *age << endl;

delete age;

cout << "\n";
return 0;
}

Friday, May 29, 2009

Using Mouse In C/C++

Mouse can be used in text mode as well as in graphics mode. Usually it is used in graphics mode. Hence we must first change over to graphics mode. In my program the function initgraph() is responsible for switching the mode from text to graphics .DETECT is a macro defined in 'graphics.h'. It requests initgraph() to automatically determine which graphics driver to load in order to switch to the highest resolution graphics mode. The initgraph() function takes three parameters, the graphics driver, the graphics mode and the path to the driver file.

Once the driver has been loaded, initgraph() sets up the numeric values of the graphics mode chosen in the variables gd and gm respectively. Here I am assuming that the driver files are in the directory 'c:\tc\bgi'. Hence the path passed to initgraph() is 'c:\tc\bgi'.

The various mouse functions can be accessed by setting up the AX register with different values (service number) and issuing interrupt number 51. The functions are listed bellow

Interrupt Service Purpose
51 0 Reset mouse and get status
Call with AX = 0
Returns: AX = FFFFh If mouse support is available
Ax = 0 If mouse support is not available

51 1 Show mouse pointer
Call with AX = 1
Returns: Nothing

51 2 Hide mouse pointer
Call with AX = 2
Returns: Nothing

51 3 Get mouse position and button status
Call with AX = 3
Returns: BX = mouse button status
Bit Significance
0 button not pressed
1 left button is pressed
2 right button is pressed
3 center button is pressed
CX = x coordinate
DX = y coordinate

51 4 Set mouse pointer position
Call with AX = 4
CX = x coordinate
DX = y coordinate
Returns: Nothing

51 7 Set horizontal limits for pointer
Call with AX = 7
CX = minimum x coordinate
DX = maximum x coordinate
Returns: Nothing

51 8 Set vertical limits for pointer
Call with AX = 8
CX = minimum y coordinate
DX = maximum y coordinate
Returns: Nothing

Let us consider a program which makes use of the above functions.


#include
#include
#include
#include
union REGS in,out;

int callmouse()
{
in.x.ax=1;
int86(51,&in,&out);
return 1;
}
void mouseposi(int &xpos,int &ypos,int &click)
{
in.x.ax=3;
int86(51,&in,&out);
click=out.x.bx;
xpos=out.x.cx;
ypos=out.x.dx;
}
int mousehide()
{
in.x.ax=2;
int86(51,&in,&out);
return 1;
}
void setposi(int &xpos,int &ypos)
{
in.x.ax=4;
in.x.cx=xpos;
in.x.dx=ypos;
int86(51,&in,&out);
}
int main()
{
int x,y,cl,a,b;
clrscr();
int g=DETECT,m;
initgraph(&g,&m,"c:\tc\bgi");
a=100;
b=400;
setposi(a,b);
callmouse();
do
{
mouseposi(x,y,cl);
gotoxy(10,9);
printf("\n\tMouse Position is: %d,%d",x,y);
printf("\n\tClick: %d",cl);
printf("\n\tPress any key to hide the mouse");
}while(!kbhit());
getch();
mousehide();
printf("\n\n\tPress any key to Exit");
getch();
}



The above program makes use of the following functions:

callmouse( )

mouseposi( )

mousehide( )

setposi( )

callmouse() :- In this function AX is set to "1". When this function is called in main() it displays the mouse pointer. The position of the pointer can be changed by using the mouse.

mousehide() :- In this function AX is set to "2".When this function is called in main() it hides the mouse pointer. This function is useful while drawing figures, first the mouse pointer is kept hidden, then the figure is been drawn and again the mouse pointer is been called.

mouseposi() :- In this function AX is set to "3". This function returns the position of the mouse pointer. It contains three parameters,they are xpos,ypos,click. xpos and ypos returns the position of x co-ordinate and y co-ordinate respectively. Click is the integer variable which returns the values 1,2,3 corresponding to the button pressed on the mouse and 0 for buttons being not pressed.


note: while loop

kbhit: If any key is pressed kbhit returns nonzero integer; if not it returns zero

setposi() :- In this function AX is set to "4". This function sets the mouse pointer to specific position . CX is been loaded by x co-ordinate of the mouse pointer and DX is been loaded with the y co-ordinate of the mouse pointer.

Let us consider another program


#include
#include
#include
#include
union REGS in,out;

int callmouse()
{
in.x.ax=1;
int86(51,&in,&out);
return 1;
}
void restrictmouseptr(int x1,int y1,int x2,int y2)
{
in.x.ax=7;
in.x.cx=x1;
in.x.dx=x2;
int86(51,&in,&out);
in.x.ax=8;
in.x.cx=y1;
in.x.dx=y2;
int86(51,&in,&out);
}
int main()
{
int x,y,cl,a,b;
clrscr();
int g=DETECT,m;
initgraph(&g,&m,"c:\tc\bgi");
rectangle(100,100,550,400);
callmouse();
restrictmouseptr(100,100,550,400);
getch();
}

The above program makes use of the following functions:

Horizontal ( )

Vertical( )

Horizontal()
:- In this function AX is set to "7". Its sets the horizontal barrier for the pointer which restricts the mouse pointer to pass that limit. CX is been loaded with the minimum x co-ordinate and Dx is been loaded with the maximum x co-ordinate.

Vertical() :- In this function AX is set to "8".Its sets the vertical barrier for the pointer which restricts the mouse pointer to pass that limit. CX is been loaded with the minimum y co-ordinate and Dx is been loaded with the maximum y co-ordinate.