Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printf( "%c", 1) return smiley face instead of coded char for 1

This is my code

#include <stdio.h>

int x,y;

int main( void )
{
    for ( x = 0; x < 10; x++, printf( "\n" ) )
        for ( y = 0; y < 10; y++ )
            printf( "%c", 1 );

    return 0;
}

It returns smiley faces. I searched everywhere for a code for smiley face or a code for 1 but I didn't manage to find any links whatsoever or any explanation why char value for 1 returns smiley face, when the ascii code for 1 is SOH. I researched answers for this question but I didn't find any answers that explain why this happens.

like image 209
maltkat Avatar asked May 26 '16 08:05

maltkat


3 Answers

The output varies among different terminals. For example, on my OS X default terminal, no characters are output.

In your case, is output presumably due to some historical reasons. In short, this is because code page 437, which maps byte 0x01 to U+263A, is the character set of MS-DOS.

like image 81
nalzok Avatar answered Sep 18 '22 20:09

nalzok


Because 1 isn't a printable character code. If you want '1' you need to write it with the character literal:

 printf( "%c", '1' );
            // ^^^
like image 32
πάντα ῥεῖ Avatar answered Sep 21 '22 20:09

πάντα ῥεῖ


If you use a number, you'll select a character number from ASCII table, if you use a char you'll find the char.

Example: this code prints the ASCII character number 65:

printf( "%c", 65 ); // Outputs: A

This code prints the letter A:

printf( "%c", 'A' ); // Outputs: A
like image 22
Danilo Calzetta Avatar answered Sep 19 '22 20:09

Danilo Calzetta