Monday, January 14, 2008

What is the output of this C++/C Program?

When compiled using GCC compiler, can you tell what is the output of the following program?

int main()
int y=10,p=20;
int num[10]={0};
int x=10,z=4;

num[-2] = -2;
num[10] = 10;

This program is supposed to be compiled on SunOS, using GCC compiler. Running it on different machine might give a totally different output.

If you run this program, you would understand how dangerous is C++ arrays, if not properly coded. Ofcourse this program does not actually corrupt your system but it does corrupt one of the variables and at times this might be dangerous.

Courtesy: Got this snippet from Dr. Dave's class. But a different example. I really liked this simple program that conveys a very big idea.

No comments: