C printf %d incorrect value with leading zeros? [duplicate]

只愿长相守 提交于 2019-12-04 05:58:04

问题


The C function printf seems to print different values depending on whether or not leading zeros are present.

I was trying to determine the numerical values for the mode argument in the Linux 'open' system call.

printf("mode:%d\n",S_IRWXU);
printf("mode:%d\n",00700);

both gave me 448, while

printf("mode:%d\n",700); gives me 700, as I would expect from both.

What is going on here?

I am using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609


回答1:


A numerical constant with one or more leading zeros is an octal constant, while one without a leading zero is a decimal constant and one with a leading 0x is a hexadecimal constant. This holds in any context, whether the value is passed to printf or any other function.

In the case of printf, you're using the %d format specifier which prints the value in decimal. If you pass in an octal constant, you'll see the decimal value of that octal number. In this example, 0700b8 == 7 * 8^2 + 0 * 8^1 + 0 * 8^0 == 7 * 64 == 448b10

If you're dealing with file permissions, those values are typically denoted as octal, so you should always use a leading 0 with those.



来源:https://stackoverflow.com/questions/47294478/c-printf-d-incorrect-value-with-leading-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!