Cohen-Sutherland Line Clipping Algorithm (C++)

static int LEFT=1,RIGHT=2,BOTTOM=4,TOP=8,xl,yl,xh,yh;
int getcode(int x,int y){
int code = 0;
//Peform Bitwise OR to get outcode
if(yyl) code |=BOTTOM;
if(xxh) code |=RIGHT;
return code;
void main(){
int gdriver = DETECT,gmode;
int x1,y1,x2,y2;

int outcode1=getcode(x1,y1), outcode2=getcode(x2,y2);
int accept = 0;                                                                                              //decides if line is to be drawn
float m =(float)(y2-y1)/(x2-x1);
if(outcode1==0&&outcode2==0){                                                     //Both points inside. Accept line
accept = 1;
}else if((outcode1 & outcode2)!=0){                                                  //AND of both codes != 0.Line is outside. Reject line
int x,y;
int temp;
if(outcode1==0) temp = outcode2;                                                   //Decide if point1 is inside. if not calculate intersection
else temp = outcode1;

if(temp & TOP){                                   //Line clips top edge
x = x1+ (yh-y1)/m;
y = yh;
}else if(temp & BOTTOM){              //Line clips bottom edge
x = x1+ (yl-y1)/m;
y = yl;
}else if(temp & LEFT){                    //Line clips left edge
x = xl;
y = y1+ m*(xl-x1);
}else if(temp & RIGHT){                //Line clips right edge
x = xh;
y = y1+ m*(xh-x1);
if(temp == outcode1){                   //Check which point we had selected earlier as temp, and replace its co-ordinates
x1 = x;
y1 = y;
outcode1 = getcode(x1,y1);
x2 = x;
y2 = y;
outcode2 = getcode(x2,y2);
cout<<“After clipping:”;
if(accept) line(x1,y1,x2,y2);

Tech Tip: Migrate your programming and testing environment into the cloud to access your essential programming tools remotely from anywhere on any device (PC/Mac/Android/iOS) with high performance hosted windows virtual desktop from with endurable technical assistance from

6 thoughts on “Cohen-Sutherland Line Clipping Algorithm (C++)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.