Looking for a way to delay the execution of your program?
Well, delay() function is gone, but Sleep() and SleepEx() Windows functions are here to stay:
For example, if you want to delay your program execution for 10 seconds, call Windows API function Sleep() with 10*1000 (convert seconds to milliseconds):
Sleep( 10000 );
Saturday, February 23, 2008
How to put a delay !!!
Find out if the CAPS LOCK is on
Here's a function you can use to find out if the CAPS LOCK is on:
function IsCapsLockOn : boolean;
begin
Result := 0 <>
(GetKeyState(VK_CAPITAL) and $01);
end;
Global exception handler
Although it's easy enough to catch errors (or exceptions) using "try / catch" blocks, some applications might benefit from having a global exception handler. For example, you may want your own global exception handler to handle "common" errors such as "divide by zero," "out of space," etc. Thanks to TApplication's "OnException" event -- which occurs when an unhandled exception occurs in your application, it only takes three (or so) easy steps get our own exception handler going:
1. Declare your custom exception handler in your form's "public declarations" section. For example, if your form is named "Form1:"
{ Public declarations }
{ begin new code }
procedure MyExceptionHandler(
Sender : TObject; E : Exception );
{ end new code }
2. Define your exception handler in the "implementation" section:
procedure TForm1.MyExceptionHandler(
Sender : TObject; E : Exception );
var
wRetVal : Word;
begin
wRetVal := MessageDlg(
{
E.Message contains the
actual error message
we'll customize it a bit...
}
'ERROR: ' + E.Message,
mtError,
mbAbortRetryIgnore,
0
);
case wRetVal of
mrAbort:
begin
{ handle "Abort" here... }
end;
mrRetry:
begin
{ handle "Retry" here... }
end;
mrIgnore:
begin
{ handle "Ignore" here... }
end;
else
begin
{
handle "other" action here...
for example, if user choose to
close the message box without
clicking on any buttons
}
end;
end;
{
you could also call the default
exception handler:
Application.ShowException( E );
}
end;
3. Finally, assign the newly created exception handler to your application's OnException event.
procedure
TForm1.FormCreate(Sender: TObject);
begin
{ begin new code }
Application.OnException :=
MyExceptionHandler;
{ end new code }
end;
Say no to program closings !!!
Here's how to prompt users whether they really want to exit your program or not (regardless of how they choose to close it):
Select your form (named "Form1" for example) and double click on its "OnCloseQuery" event
Define the "FormCloseQuery" procedure as follows:
Code:
procedure TForm1.FormCloseQuery(
Sender: TObject;
var CanClose: Boolean);
begin if(mrNo = MessageDlg(
'Are you sure you want to exit?',
mtInformation,
[mbYes, mbNo],
0)) then
begin
CanClose := False;
end;
end;
For Delphi Code contact me at sagar.agl@gmail.com
Wednesday, February 20, 2008
Overloading the Parenthesis () Operator
First, I want to apologize to my readers for not being able to post lately, partly due to me being very busy these days;-)
As we all know, there are certain ways by which we can pass data to objects (of class). We can pass values during the time of construction as below: class-name ob-name(values);
Or we may define a member function to accept data which can be called as below: class-name ob-name;
ob-name.set(values);
Where set is the member function of the class.
But actually there is one more way to do so, yeah you guessed it right!, by overloading the parenthesis () operator.
Parenthesis () operator like other operators is overloaded with the following prototype: ret-type operator()(arg1, arg2,...);
It is a unary operator hence the only argument passed to this function (implicitly) is this pointer. The argument list may contain any number of arguments as you wish to pass.
The following example program illustrates the overloading of parenthesis () operator in C++.
// Overloading Parenthesis ()
// Operator
#include
class myclass
{
int a,b;
public:
myclass(){}
myclass(int,int);
myclass operator()(int,int);
void show();
};
// ------------------------
// --- MEMBER FUNCTIONS ---
myclass::myclass(int x, int y)
{
a=x;
b=y;
}
myclass myclass::operator()(int x, int y)
{
a=x;
b=y;
return *this;
}
void myclass::show()
{
cout<}
// --- MEMBER FUNCTIONS ---
// ------------------------
void main()
{
myclass ob1(10,20);
myclass ob2;
ob1.show();
// it's a nice way to pass
// values, otherwise we
// would have to define and
// call a member/friend function
// to do so
ob2(100,200);
ob2.show();
}
Classes and Structures in C++
In C, a structure (struct) gives us the ability to organize similar data together. You may wonder what I said. It is so in C, this is because structure is one of the few things which is more or less entirely different in the two languages (C and C++).
In C++, the role of structures is elevated so much as to be same as that of a class. In C, structure could only include data as variables and arrays but in C++ they can also include functions, constructors, destructors etc. and in fact everything else that a class can. Knowing this, it wouldn’t be wrong to say that in C++, structures are an alternate way of defining a class. However there are some differences.
Look at the following code:
// First difference between a class
// and a structure in C++
// define a structure
struct mystruct
{
char name[25];
int id_no;
};
void main()
{
mystruct a;
// in C, it is necessary to
// include the struct keyword
// Example:
// struct mystruct a;
...
...
...
}
In C, we must declare an object of a structure by using the keyword struct but in C++ it is optional to do so (just like a class).
Another difference is the fact that all the data or functions inside a struct are public by default contrary to a class, inside which scope is private by default.
It is obvious from the following code:
// Second difference between a class
// and a structure in C++
// define a structure
struct mystruct
{
// public by default
// So convenient to start with
// public declarations
void func1();
void func2();
...
...
private:
// now private
int data1;
int data2;
...
...
};
// define a class
class myclass
{
// private by default
int data1;
int data2;
...
...
public:
// now public
void func1();
void func2();
...
...
};
While you’ve got the power, you should not define a class as a struct since it is not a good practice. Structures and classes should be used as per their original purposes to avoid unnecessary complications and misunderstandings.
Introduction to Function Overloading in C++
Let us start this with a question!
All of you know that we cannot have two variables of the same name, but can we have two Functions having the same name.
The answer is YES, we can have two functions of the same name by a method known as function overloading and the functions having the same name are known as overloaded functions.
So, what’s the use of Function Overloading
Function overloading is one of the most powerful features of C++ programming language. It forms the basis of polymorphism (compile-time polymorphism).
Most of the time you’ll be overloading the constructor function of a class.
How function overloading is achieved
One thing that might be coming to your mind is, how will the compiler know when to call which function, if there are more than one function of the same name.
The answer is, you have to declare functions in such a way that they differ either in terms of the number of parameters or in terms of the type of parameters they take.
What that means is, nothing special needs to be done, you just need to declare two or more functions having the same name but either having different number of parameters or having parameters of different types.
Example 1: Overloading Functions that differ in terms of NUMBER OF PARAMETERS
//Example Program in C++
#include
//FUNTION PROTOTYPES
int func(int i);
int func(int i, int j);
void main(void)
{
cout<
cout< }
int func(int i)
{
return i;
}
int func(int i, int j)
{
return i+j;
}
Example 2: Overloading Functions that differ in terms of TYPE OF PARAMETERS
//Example Program in C++
#include
//FUNTION PROTOTYPES
int func(int i);
double func(double i);
void main(void)
{
cout<
cout< }
int func(int i)
{
return i;
}
double func(double i)
{
return i;
}
One more Question, is the program below, valid?
//Example Program in C++
#include
//FUNTION PROTOTYPES
int func(int i);
double func(int i);
void main(void)
{
cout<
cout< }
int func(int i)
{
return i;
}
double func(int i)
{
return i;
}
No, because you can’t overload functions if they differ only in terms of the data type they return.
I Hope this article throws some light on function overloading!
Good-Bye for now
Sorting Two-Dimensional Arrays
Do you know how a 2D array is stored in the memory while the memory is only one-dimensional?
The answer is simple, all the arrays are stored linearly in the memory, be it 2D array or 3D, only the representation is such that to make it easy to reference.
Therefore, if a two-dimensional array has the following elements:
1 2 3
4 5 6
7 8 9
in the memory, it will be like this:
1 2 3 4 5 6 7 8 9
just because memory is linear, and cannot have dimensions. It is the language that represents 2 D arrays as such while in the memory it is always linear.
This property of 2D arrays will be used to sort them, because sorting linear data is much easier.
We don’t need much discussion on this, so here is the example program, please read the comments where all things are elaborated
// --Sorting Program--
// -------------------
// Example Program to sort
// 2D array using linear
// representation of the array
#include
#define MAX 3
void main(void)
{
int arr[MAX][MAX];
int i,j,temp;
int *arr_ptr;
for(i=0;i>arr[i][j];
// we have taken a pointer
// to the 2D array to
// represent it linearly
// C-style type cast
// is necessary here
arr_ptr=(int*)arr;
// sorting is done here.
// selection sort method of
// sorting is employed here
// you can use whichever
// method you like
// here MAX*MAX is used
// because the no. of elements
// in the linear representation
// of the 2D array has that
// many elements
for(i=0;i<((MAX*MAX)-1);i++) for(j=i+1;j<(MAX*MAX);j++) if(*(arr_ptr+i)>*(arr_ptr+j))
{
temp=*(arr_ptr+i);
*(arr_ptr+i)=*(arr_ptr+j);
*(arr_ptr+j)=temp;
}
// sorting is done till here
cout<<<" "<<
Good-Bye!
Introduction to Dynamic Memory Allocation in C++
Suppose you are making a C++ program to store a particular number (specified by the user at runtime) of phone numbers. What will you do? You cannot declare array of 10 or 20 elements because you don’t know how many numbers the user will enter. He may want to enter 1, 10 or even 100 phone numbers.
So what will you do?
Actually, you can do two things to achieve this, that are listed below:
-
You can create a very large int(eger) array (say, of 500 elements) , in this case whether the user wants to store 1 or 500 phone numbers, the memory used will always be the same (large!).
-
You can make use of C++’s dynamic memory allocation to allocate only the needed amount of memory.
The first choice is a very bad way of programming, nevertheless it works fine, you should never employ such an inefficient method of programming.
So, you are left with only one choice to use the Dynamic Memory Allocation of C++ programming language, that I will be discussing in this article.
As is clear from the above example, dynamic memory allocation is needed when you don’t know the program’s memory needs beforehand.
Allocating Memory
Dynamic memory is allocated by the new keyword. Memory for one variable is allocated as below:
ptr=new DataType (initializer);
Here,
-
ptr is a valid pointer of type DataType.
-
DataType is any valid c++ data type.
-
Initializer (optional) if given, the newly allocated variable is initialized to that value.
Ex.
//Example Program in C++
#include
void main(void)
{
int *ptr;
ptr=new int(10);
cout<<*ptr; delete ptr;
}
This is will allocate memory for an int(eger) having initial value 10, pointed by the ptr pointer.
Memory space for arrays is allocated as shown below:
ptr=new DataType [x];
Here,
-
ptr and DataType have the same meaning as above.
-
x is the number of elements and C is a constant.
Ex.
//Example Program in C++
#include//arrays are freed-up like this
void main(void)
{
int *ptr, size;
cin>>size;
ptr=new int[size];
delete []ptr;
}
Freeing-Up Allocated Memory
Unlike static variables, c++ will not free-up the memory allocated through dynamic allocation. Its your duty to free them up. delete keyword is used to free-up the allocated memory.
delete ptr;
Arrays are deleted in a slightly different manner as shown below:
delete []ptr;
It’s easy to forget to free the allocated memory because C++ compiler won’t inform you that you are doing this. It’s your job and should always be done.
Now let me show you an example of dynamic memory allocation in action:
//Example Program in C++
#include//input ph. numbers
void main(void)
{
int *ptr, size;
cout<<"How many PH. Numbers do you wish to enter:"; cin>>size;
ptr=new int[size];//allocate memory
for (int i=0;i<<"Enter PH. NO."<<<" :"; cin>>ptr[i]; //output ph. numbers
}
cout<<"\n\n\n PH. NOs. are\n"; for (i=0;i<<"\nPH. NO."<<<" :"< cout<delete []ptr;//free-up memory
}
Good-Bye!
Operation on Bits and Bitwise Operators
OK guys, this is my first post in the New Year 2008, I thought of posting it earlier but at last I didn’t. It’s already been so long since I posted so let’s keep everything aside and talk just about what we have for today. ;-)
I was sitting the other day thinking about what to write for a post here. Suddenly I realized that we have discussed operations on matrices, arrays, and what not but we haven’t had the chance to talk anything about the most fundamental thing a computer understands. Yeah, Operation on Bits.
Bits can have only two values either ON (1) or OFF (0). In this article, we’ll be discussing about the different operations which can be performed on bits. One thing to note here is, we don’t perform these operation on single bits but rather on a group of bits (byte(s)). So even though Bitwise operators operate on bits its almost always a part of a group (byte, which makes up each data type), it means we can do bitwise operations on any data type.
BTW, the operators that perform operation on bits are called Bitwise Operator and such operations are known as Bitwise Operations
The six bitwise operators are listed below:
& | AND |
| | OR |
^ | XOR |
>> | Right shift |
<< | Left shift |
~ | One’s complement |
For this post we’ll only be discussing &(AND) and | (OR) operators leaving the rest for future posts ;-)
Bitwise AND (&) Operator: First thing, it’s nothing to do with the Logical (&&) operator, both are different.
Now, if you know something about Logic Gates then you might already know about this. For the rest of us, it does an AND mask on bits.
So, suppose if we have two separate bytes having binary values as 00100000 and 00100001 then doing AND operation would give us the following result.
First Byte: | 00100000 00100001 |
Result: | 00100000 |
The truth table for this would be:
First Bit | Second Bit | & (AND) |
1 1 0 0 | 1 0 1 0 | 1 0 0 0 |
As the Logic AND Gate does, it takes two bits (from the two separate bytes) and if both of them are ON (1) then only it gives ON (1) in all other cases it gives OFF (0). So starting from the right there is 0&1->0, 0&0->0,…, 1&1->1 and so on.
Bitwise OR (|) Operator: Here again, both OR (||) and Bitwise OR (|) are different.
The following example is sufficient for you all to understand its operation.
First Byte: | 00100000 00100001 |
Result: | 00100001 |
Truth table
First Bit | Second Bit | & (OR) |
1 1 0 0 | 1 0 1 0 | 1 1 1 0 |
There won’t be any example program here because to fully understand these operators we need to express data as bits (binary form) and see how the operations change them. Since decimal to binary conversion programs require some bitwise operations that we’ve yet to discuss so I think it’ll be pointless to have such programs now!
P.S. An integer in 32-Bit (Windows) environment is 4 bytes long. Short int is half of that
8 bits make up one byte.