Trivial C question: iterating through chars

Robert G. Brown rgb at
Fri Apr 20 09:09:46 PDT 2001

On Fri, 20 Apr 2001, Chris Richard Adams wrote:

> I'd like to view all the ASCII chars on my system.  I tried:
> char ch = 'NUL';
> int i;
> for ( i = 0; i < 500; i++)
> 	printf("Char: %c/n", ch + i");
> This fails.

Simple/trivial errors.  Extra ", backwards /n, 'NUL' should just be 0 or
NULL, int + char casts to int, not char, so you need a cast to char
which means that you might as well not bother with a char at all,


 int i;

 for(i=0;i<256;i++) printf("Char[%d] = %d\n",i,(char)i);

is much easier and works charmlike.  Note that going higher than 255 is
not useful if char is a single byte, as it is on many systems.  ASCII in
any event is only 0-255.  Note that this will probably make your screen
beep when you run it and will generate a bit of garbage when you hit
control characters that don't really print.

For fun you can do this with the following perl one-liner:

perl -e 'for($i=0;$i<256;$i++){printf("Char[%d]: %c\n",$i,$i ) }'

which saves the effort of compile and so forth.  Note that the perl is
nearly identical to the C except you don't really need the cast (you
probably don't in C either but the compiler will complain if you don't
and MIGHT not work -- haven't tried it).


Robert G. Brown	             
Duke University Dept. of Physics, Box 90305
Durham, N.C. 27708-0305
Phone: 1-919-660-2567  Fax: 919-660-2525     email:rgb at

More information about the Beowulf mailing list