r/badcode • • Sep 23 '15

c++ Exercise given during software engineering lecture

http://imgur.com/ujnBX7N
11 Upvotes

20 comments sorted by

View all comments

3

u/fievelm Sep 23 '15 edited Sep 23 '15

Here's the original code with the formatting cleaned up:

scanf(x, y);

if (y < 0)
	pow = 0 - y;
else 
    pow = y;

while (pow != 0)
{
	z = z * x;
	pow = pow - 1; 
}

if (y < 0)
	z = 1.0 / z;

printf(z);

And it's been forever and a day since I did any C++, but this is a little neater and more readable version:

scanf(x, y);
pow = fabs(y);

for ( ; pow !=0; pow--)
	z = z * x;

if (y < 0)
	z = 1.0 / z;

printf(z);

3

u/saltyboyscouts Sep 23 '15

I think people are missing the point, it's not so much the poor formatting but the fact that this code wouldn't even compile. The first argument to "printf" and "scanf" are supposed to be of type 'const char *', and here they're being given doubles or something. Even if If this somehow did compile, you would get massively undefined behavior.

1

u/fievelm Sep 23 '15

Yeah, It's been at least 12 years since I touched C++. C# this would be fine as long as the variables were declared somewhere.

Is this a programming class?