You can have just one declaration in the initial position of the for
loop in C99 and later:
for (int levelCounter, usrHeight, paddIt = usrHeight - 1, hashMaker, hashCounter;
...condition...; ...increment...
)
However, you have a problem; usrHeight
is uninitialized, so paddIt
is an indeterminate value. And I had to change the type of hashMaker
to int
. You can only use one type.
Frankly, declaring that many variables in the loop control is wrong. If you do it, all of them should be initialized. Otherwise, you could use:
for (int levelCounter; ...condition...; ...increment...)
{
int usrHeight = -1, paddIt = usrHeight - 1, hashCounter = 0;
char hashMaker;
...loop body...
}
This fixes some problems. If you need the values of the variables preserved across iterations of the loop (this defines and initializes them on each iteration), then the extra variables should be defined outside the loop. You would seldom declare more than one, and even more rarely more than two, variables in a for
loop. I could almost justify:
for (int i = min, j = max; i < j; i++, j--)
which has one variable counting up while the other counts down, though you could compute j
in the body of the loop, especially if min
is 0.
Someone who presented me with (a fixed version of) the original code for code review would get very short shrift from me — go rewrite the code more clearly.
The second problem is a missing comma where the compiler said it expected a )
:
printf("%'' * paddIt %c*hashCounter"paddIt,hashMaker,hashCounter);
should be:
printf("%'' * paddIt %c*hashCounter", paddIt, hashMaker, hashCounter);
The first part of that is actually a malformed conversion specification; you might mean "%%''..."
or you might mean something else altogether, such as:
printf("%' *.*c", paddIt, hashMaker, hashCounter);
The single quote is still not relevant to the %c
conversion specifier (so the behaviour is undefined), but it is part of POSIX 2008 of printf()
— it adds thousands separators when necessary for large numbers.
I didn't notice that you already declared all the variables you mention in your for
loop. It looks as though you could reduce that loop to:
for (levelCounter = 0; levelCounter <= usrHeight; levelCounter++)
{
printf("%.*s", paddIt, "");
for (int i = 0; i < hashCounter; i++)
putchar('#');
paddIt = paddIt - 1;
hashCounter = hashCounter + 1;
}
This uses the information from a comment about the intended format which was not clear from the original question.