Parameters
| Name | Type | Description |
|---|---|---|
none | void | clearviewport() takes no arguments and clears the active viewport region only. |
If no custom viewport was created, the default viewport usually spans the normal drawing area, so the behavior can appear similar to cleardevice(). The important distinction shows up when a program intentionally limits drawing to a smaller box or panel.
Return Value
clearviewport() returns void. It does not report how much was cleared or whether the viewport had content before the call. It simply resets the active viewport area to the background color.
Code Examples
Clear only a boxed drawing region
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
rectangle(60, 60, 580, 380);
setviewport(80, 80, 560, 360, 1);
setcolor(YELLOW);
circle(120, 90, 50);
getch();
clearviewport();
setcolor(LIGHTCYAN);
rectangle(140, 100, 280, 220);
getch();
closegraph();
return 0;
}
The outer frame remains visible because only the viewport interior is cleared. This is the main benefit of viewport-local clearing.
Refresh a chart panel without touching the title
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
outtextxy(210, 30, "Status Dashboard");
rectangle(90, 80, 550, 340);
setviewport(100, 90, 540, 330, 1);
setcolor(LIGHTGREEN);
line(20, 180, 400, 180);
getch();
clearviewport();
setcolor(LIGHTRED);
bar(40, 120, 120, 180);
bar(160, 90, 240, 180);
bar(280, 60, 360, 180);
getch();
closegraph();
return 0;
}
The title stays in place because it was drawn outside the viewport. Only the graph panel is refreshed.
Use it as a local animation area
#include <graphics.h>
#include <conio.h>
#include <dos.h>
int main() {
int gd = DETECT, gm;
int x;
initgraph(&gd, &gm, "");
rectangle(100, 120, 540, 300);
setviewport(110, 130, 530, 290, 1);
for (x = 30; x <= 360; x += 10) {
clearviewport();
setcolor(WHITE);
circle(x, 80, 20);
delay(30);
}
getch();
closegraph();
return 0;
}
The moving circle is limited to a specific animation box while the outer border stays stable.
Common Mistakes
Expecting the whole screen to clear
If a viewport is active, only that viewport is affected. This is useful when intentional, but confusing when you expected a full-screen reset.
Forgetting that viewport coordinates are local
Inside a viewport, many coordinates become relative to that viewport origin. A line drawn at (20, 20) is no longer near the full-screen top-left corner.
Not defining the viewport before using it
If you never called setviewport(), the behavior may look like a normal screen clear and hide the real difference between the two clear functions.
Try it online
Run the examples and comment out the setviewport() line once to see how the clearing behavior changes.