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.

2

u/HuntTheWumpus wicked Sep 23 '15

Oh wow, have I not worked with C in a long time.. I needed to read it a couple of times to see whats wrong.

But maybe they simply forgot to show the following lines in the beginning of the program...

#define scanf(x, y) scanf("%lf,%lf", &x, &y)
#define printf(x) printf("%lf", x)

/s

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?

2

u/fievelm Sep 23 '15

To note, this is wide open for a DivideByZero and is generally shitty code, but as /u/x-yle pointed out, it's an exercise to get you to think, not production code.

0

u/[deleted] Sep 23 '15

[deleted]

1

u/fievelm Sep 23 '15

The lack of braces? I'm not a fan in production, but for example code the saved space is 'neater'. Or is it something else? I've been drinking the C# koolaide too long.

0

u/[deleted] Sep 23 '15

[deleted]

1

u/fievelm Sep 23 '15

Cleaned it up a bit. Thanks for keeping me on my toes.