Initialization
Graphics Initialization
Before drawing anything using graphics.h, you must initialize the graphics system properly. Initialization switches the program from text mode to graphics mode and loads the required graphics driver.
On This Page
initgraph()
Syntax
void initgraph(int *graphdriver, int *graphmode, const char *pathtodriver);
Description
Initializes graphics mode, loads the driver, and prepares the display for drawing operations.
Parameters
graphdriver: pointer to graphics driver variable.graphmode: pointer to graphics mode variable.pathtodriver: path to BGI drivers. In many modern/online setups,""works.
In student programs, using DETECT with initgraph() is usually enough.
Example
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
circle(200, 200, 100);
getch();
closegraph();
return 0;
}
detectgraph()
Syntax
void detectgraph(int *graphdriver, int *graphmode);
Detects driver and mode without initializing graphics. Useful if you want to inspect availability before calling initgraph().
int gd, gm; detectgraph(&gd, &gm); initgraph(&gd, &gm, "");
graphresult()
Syntax
int graphresult(void);
Returns status of the last graphics operation. You should check it after initgraph().
If return value is grOk, initialization succeeded.
grapherrormsg()
Syntax
char *grapherrormsg(int errorcode);
Converts a graphics error code into a readable message. Typically used with graphresult().
closegraph()
Syntax
void closegraph(void);
Shuts down graphics mode and restores text mode.
Always call closegraph() before program termination.
restorecrtmode()
Syntax
void restorecrtmode(void);
Restores text mode without fully closing graphics. Rare in beginner programs.
Typical Initialization Flow
- Declare driver/mode variables.
- Call
initgraph(). - Check
graphresult(). - Run drawing operations.
- Wait for input.
- Call
closegraph().
Example with Error Handling
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
int errorcode = graphresult();
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));
return 1;
}
circle(200, 200, 100);
getch();
closegraph();
return 0;
}
Common Initialization Errors
- BGI driver not found.
- Incorrect BGI path in older Turbo C setups.
- Running graphics.h in unsupported compilers.
- Missing graphics drivers.
- Incorrect graphics mode selection.
Important reminders: graphics.h is not part of standard C, initialization must happen before drawing, and closegraph() must be called before exit.