C - Multiply char by int
Solution 1
for ( size_t ii = 0; ii < 5; ++ii )
putchar('#');
Solution 2
Use a loop to print it multiple times.
In C, a symbol between ''
has a type char
, a character, not a string. char
is a numeric type, same as int
but shorter. It holds a numerical representation of the symbol (ASCII code). Multiplying it with an integer gives you an integer.
A string, contained between ""
is an array of characters. The variable will store a pointer to the first character.
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
Before I ask my question let me just say that I am a newbie to C, and do not know how to do a lot in it.
Anyway, the problem is that I need to print a specific number of characters. I first used Python, because that was a language that I was familiar with, and wrote this very simple program.
x = 5 print('#' * x)
This is what I want to achieve, but in C. Sorry if this is a duplicate or a stupid question, but I have been puzzled and without answers, even after looking on the internet.
-
Grzegorz Szpetkowski over 9 yearsIn C character constants are of type
int
. You probably confusing with C++. -
ftynse over 9 yearsWell, I may have oversimplified. But an explanation of what is an implementation-defined behavior and how it is supposed to work for 'ab' or for multibyte characters does not belong to this question. For curious, stackoverflow.com/questions/20764538/type-of-character-constant
-
Tim Čas over 9 years@ftynse: Type of character constants is not implementation-defined. It is always
int
(C99,6.4.4.4p10
); for wide constants, it iswchar_t
(p11
). -
chux - Reinstate Monica over 9 years@ftynse The
sizeof('a') == sizeof(int)
- this is not a implementation-defined behavior issue. "An integer character constant has typeint
." -
Arkku over 9 yearsUsing
printf
to in a loop to print individual characters is overkill; hereputchar
would suffice. -
Admin over 9 yearsEven though I chose another answer to my question, I did like your explanation. Thank you!
-
Admin over 9 yearsNever knew of the putchar function before now, Thanks!