Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does putchar('0' + num); do?

Tags:

c

putchar

I am trying to understand how the putchar('0' + r); works. Below, the function takes an integer and transform it to binary.

void to_binary(unsigned long n)
{
   int r;
   r = n % 2;
   if (n >= 2)
      to_binary(n / 2);
   putchar('0' + r);
}

I google the definition of putchar but I didn't find this. To test it, I added a printf to see the value of the r:

void to_binary(unsigned long n)
{
   int r;
   r = n % 2;
   if (n >= 2)
      to_binary(n / 2);
   printf("r = %d and putchar printed ", r);
   putchar('0' + r);
   printf("\n");
}

and I run it (typed 5) and got this output:

r = 1 and putchar printed 1
r = 0 and putchar printed 0
r = 1 and putchar printed 1

So I suppose that the putchar('0' + r); prints 0 if r=0, else prints 1 if r=1, or something else happens?

like image 995
yaylitzis Avatar asked Jan 21 '14 10:01

yaylitzis


People also ask

What does Putchar 0 mean?

'0' represents an integer equal to 48 in decimal and is the ASCII code for the character 0 (zero). The ASCII code for the character for 1 is 49 in decimal. '0' + r is the same as 48 + r .

What does the function putchar () do?

putchar is a function in the C programming language that writes a single character to the standard output stream, stdout. Its prototype is as follows: int putchar (int character) The character to be printed is fed into the function as an argument, and if the writing is successful, the argument character is returned.

Can Putchar print numbers?

As we know that the putchar() is used to print only characters. We can use this function to print each digit of the number. When one numeric value is passed, we have to add character '0' with it to get the ASCII form.

What is the syntax of Putchar?

Syntax. The putchar() function takes an integer argument to write it to stdout. The integer is converted to unsigned char and written to the file. Upon success, the putchar() function returns the character represented by ch ; upon failure, the function returns EOF and sets the error indicator on stdout.


1 Answers

In C '0' + digit is a cheap way of converting a single-digit integer into its character representation, like ASCII or EBCDIC. For example if you use ASCII think of it as adding 0x30 ('0') to a digit.

The one assumption is that the character encoding has a contiguous area for digits - which holds for both ASCII and EBCDIC.


As pointed out in the comments this property is required by both the C++ and C standards. The C standard says:

5.2.1 - 3

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

like image 113
cnicutar Avatar answered Oct 12 '22 12:10

cnicutar