Functions Before & After main()

C/C++

Functions Before & After main()
For this purpose compiler directive #pragma is used.

Syntax:
#pragma startup FUNCTION_NAME
#pragma exit FUNCTION_NAME

#pragma startup executes the function named FUNCTION_NAME before the main() function
pragma exit executes the function named FUNCTION_NAME after the main() function.

Function declaration of FUNCTION_NAME must be before startup and exit pragma directives and function and also it must not take any argument and return void.

The following code illustrates the use of #pragma startup & exit.


#include "iostream.h"
#include "conio.h"

void BeforeMain()
{
clrscr();
cout << "Function BeforeMain() Called.\n\n";
}

void AfterMain()
{
cout << "Function AfterMain() Called.\n\n";
getch();
}

#pragma startup BeforeMain
#pragma exit AfterMain

void main()
{
cout << "Function main() called.\n\n";
}

Output :-


Compiler Used - TURBO C++ Version 3.0

Download the source code and exe files from here.


No comments: