Thursday, December 11, 2008

DEV C++ the problem with the system("PAUSE")

when you are writing a console mode win32 application using DEV C++ IDE , this is the
automatically generated main method that you get.

int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}


some strange things are there , well nothing to worry , EXIT_SUCCESS is already defined as 0 .
so it's same like you saying

return 0;

anyway , what's the hell that system("PAUSE") , well
"PAUSE" is just a dos command , you can also "dir /p" or run any dos command using like that.

Just change your main method like this and compile and run.

int main(int argc, char *argv[])
{
system( "dir /p");
system ( "PAUSE");

return EXIT_SUCCESS;
}
then you will get the directory listing like this ,


so you now know what's this strange system("PAUSE"); really means is .
what it actually doing is ,
  1. suspend your program

  2. call the operating system

  3. open an operating system shell (relaunches the O/S in a sub-process)

  4. the O/S must now find the PAUSE command

  5. allocate the memory to execute the command

  6. execute the command and wait for a keystroke

  7. deallocate the memory

  8. exit the OS

  9. resume your program

so brother why this becomes a trouble for a learner , that who is newbie for the C++ programming language ?
well learning object oriented ... just write bellow simple program and see what happens .
#include
#include

using namespace std;

class A
{
public:
// the constructor
A()
{
cout<< " The constructor called " << '\n';
}

// the copy constructor
A(const A& a )
{
cout << " The copy constructor is called" << '\n';
}

~A()
{
cout << "The destructor is called "<< '\n';
}
};


void takeA(const A& a )
{

}
int main(int argc, char *argv[])
{
A a ;
// the constructor must be called.
system ( "PAUSE");
return EXIT_SUCCESS;
} // the destructor must be called.

well but the output is just like this ,

The constructor is called
Press any key to continue....
well where is the destructor call ? well my friend Press any key to continue is comes from the PAUSE dos command. If you are not sure just go to the command prompt and type PAUSE and
see what happened.
so the destructor will be called after that. But you will unable to see it unless you run this program
using the command prompt. But if you run this on the command prompt window , you will see like this . 13 Dir(s) 6,477,045,760 bytes free

G:\Dev-Cpp>main
The constructor called
Press any key to continue . . .
The destructor is called

G:\Dev-Cpp>


so that's all the magic of the system("pause") as same as system("PAUSE");


No comments: