spamsink: (lenin)
[personal profile] spamsink


В какой-то мере навеяно постом [livejournal.com profile] ivan_gandhi

Что произойдет в вашей системе и что, по-вашему, должно произойти при попытке компиляции (и, если компиляция была/должна быть успешной, то запуска) следующей программы на Си:

#include <stdio.h>
main() {
printf("%d %d %d\n", (int)(-1.0/0.0), (int)(0.0/0.0), (int)(1.0/0.0));
}

Date: 2013-11-18 09:11 am (UTC)
From: [identity profile] lionet.livejournal.com
INT_MIN, 0, INT_MAX

Потому что -inf, nan, inf.

Date: 2013-11-18 06:20 pm (UTC)
From: [identity profile] lionet.livejournal.com
Бля.

Date: 2013-11-18 09:18 am (UTC)
From: [identity profile] fregimus.livejournal.com
При компиляции: error C2124: divide or mod by zero

Microsoft (R) C/C++ Optimizing Compiler Version 17.00.60610.1

Date: 2013-11-18 04:28 pm (UTC)
From: [identity profile] fregimus.livejournal.com
Измененная программа, ниже, чисто компилируется без оптимизации, а с включенной оптимизацией я получаю то же самое сообщение, только как warning. Соображает, что дурят его!

Date: 2013-11-18 05:01 pm (UTC)
From: [identity profile] fregimus.livejournal.com
Совпадают. Но не уверен, что это в таком неопределенном случае всегда должно быть верно.

Date: 2013-11-19 06:25 am (UTC)
From: [identity profile] archaicos.livejournal.com
В каком именно месте он определённый кроме определённого наличия UB?

Date: 2013-11-18 09:21 am (UTC)
From: [identity profile] fregimus.livejournal.com
void main() {
double z = 0.0;
printf("%d %d %d\n", (int)(-1.0/z), (int)(0.0/z), (int)(1.0/z));
}


-2147483648 -2147483648 -2147483648

Date: 2013-11-18 09:22 am (UTC)
From: [identity profile] archaicos.livejournal.com
Если скомпилируется, то UB.

Date: 2013-11-19 06:14 am (UTC)
From: [identity profile] archaicos.livejournal.com
По определению?

C99:

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

Date: 2013-11-19 06:50 am (UTC)
From: [identity profile] archaicos.livejournal.com
Получил бы ты двойку за такой ответ на экзамене по Си. :)

Date: 2013-11-19 06:56 am (UTC)
From: [identity profile] archaicos.livejournal.com
А кто умеет, мучается с UB в своём коде. :)

Date: 2013-11-19 07:26 am (UTC)
From: [identity profile] archaicos.livejournal.com
В Верилоге, поди, тоже есть «тонкости» для мучений.

Date: 2013-11-19 07:33 am (UTC)
From: [identity profile] archaicos.livejournal.com
Чудно.

Date: 2013-11-19 06:52 am (UTC)
From: [identity profile] archaicos.livejournal.com
Ага, известное «It works on my computer». :)

А потом обновляешь компилятор или запускаешь другой компилятор на том же процессоре с той же ОС, и результат другой.

Date: 2013-11-18 09:31 am (UTC)
From: [identity profile] b0p0h0k.livejournal.com
-2147483648 -2147483648 -2147483648

Computer says −80000000.
Edited Date: 2013-11-18 09:33 am (UTC)

Date: 2013-11-18 09:46 am (UTC)
From: [identity profile] t-mike.livejournal.com
gcc (GCC) 4.8.2 20131017 (Red Hat 4.8.2-1)
-2147483648 -2147483648 -2147483648

clang version 3.3 (tags/RELEASE_33/rc3)
-2147483648 0 2147483647

gcc (Debian 4.6.3-14+rpi1) 4.6.3
-2147483648 0 2147483647
Edited Date: 2013-11-18 10:08 am (UTC)

Date: 2013-11-18 06:04 pm (UTC)
From: [identity profile] sab123.livejournal.com
Чего дошло? До меня пока не доходит. В-общем случае оно небось все выходит за границы представления целых, поэтому результат неопределен. Но представлять плюс-бесконечность отрицательным числом, наверное, более неправильно, чем положительным.

Date: 2013-11-19 02:38 am (UTC)
From: [identity profile] dvv.livejournal.com
Неопределённое ("undefined", 6.5.5-5) значение на то и неопределённое, что не определено. Никто не обязан в качестве неопределённого значения давать какое-то определённое значение.

Date: 2013-11-19 06:24 am (UTC)
From: [identity profile] archaicos.livejournal.com
Зачем? В подобной ситуации только в отладочных целях модно туда смотреть. Полагаться на UB нельзя независимо от IEEE-754.

Date: 2013-11-19 06:23 am (UTC)
From: [identity profile] archaicos.livejournal.com
UB нельзя использовать для проверки чего либо.

Если ты хочешь такого, но не видишь, то это ошибка в компиляторе:

The semantic rules for the evaluation of a constant expression are the same as for nonconstant expressions. 97)

97) Thus, in the following initialization,
    static int i = 2 || 1 / 0;
the expression is a valid integer constant expression with value one.
Page generated Mar. 5th, 2026 01:40 am
Powered by Dreamwidth Studios