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

2020-05-04 11:27发布

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条回答
Bombasti
2楼-- · 2020-05-04 11:37

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.

查看更多
登录 后发表回答