Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does printf statement work here, when printing integer number?

Tags:

c

#include<stdio.h>
int main()
{
    int a=034;
    printf("%d",a);
    return 0;
}

If I give a value as 034, the output is 28. if it's 028, it gives an error saying "invalid digit "8" in octal constant".

like image 264
Divya Sharvani Avatar asked Jul 10 '16 04:07

Divya Sharvani


People also ask

Does printf work on integers?

In C if you start an integer with a zero ( 0 ) then it is treated as an octal representation of the number. In octal representation there are only 8 valid digits. They are 0, 1, 2, 3, 4, 5, 6, and 7. So you can see that printf is working correctly here.

How does the printf function work?

The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.

How do I print an integer?

This number is stored in the number variable. printf("Enter an integer: "); scanf("%d", &number); Finally, the value stored in number is displayed on the screen using printf() . printf("You entered: %d", number);

Can we use printf () apart from just printing values?

The printf function of C can do a lot more than just printing the values of variables. We can also format our printing with the printf function. We will first see some of the format specifiers and special characters and then start the examples of formatted printing.


1 Answers

In C if you start an integer with a zero (0) then it is treated as an octal representation of the number. In octal representation there are only 8 valid digits. They are 0, 1, 2, 3, 4, 5, 6, and 7.

So you can see that printf is working correctly here. 034 is an octal number, which is 28 in decimal. So printf is printing correct value of int variable a which is 34 in octal, which is equivalent to 28 in decimal.

However, the error - while using 038 - is not related to the printf. You get error when you try to use a number like 038 because, you are using an octal representation - by starting the number with 0 - but you are using an invalid digit, 8 , which simply does not exist in octal number system.

P.S: If you start a number with 0x or 0X then that is treated as a hexadecimal representation of the number.

P.S: If you want to print an integer in octal format, the format specifier is %o. For example: printf("num = %o \n", num);

P.S: If you want to print an integer in hexadecimal format, the format specifiers are %x or %X. For example: printf("num1 = %x, num2 = %X \n", num1, num2);

like image 199
sps Avatar answered Oct 04 '22 01:10

sps