avva: (Default)
[personal profile] avva
(эта запись может быть интересна программистам, знающим C/C++)

Во внутреннем форуме на работе кто-то устроил опрос, который просто не могу не украсть:

[Poll #2078582]

Не смотрите в комментарии перед голосованием, там можно обсуждать правильный ответ.
Page 1 of 3 << [1] [2] [3] >>

Date: 2018-02-22 10:59 am (UTC)
From: [identity profile] mopexod.livejournal.com
Я боюсь представить себе причины опроса.
Может, есть какой-нибудь стандарт С-2017, в котором употребление знака делает выражение знаковым?

Date: 2018-02-22 11:01 am (UTC)
From: [identity profile] avva.livejournal.com
Пока что все ответы на опрос - от наивных, добрых, милых людей, которые думают, что в мире есть справедливость, а в его устройстве - разум.

Date: 2018-02-22 11:03 am (UTC)
From: [identity profile] mopexod.livejournal.com
Так. Я уже немного забеспокоился.

Date: 2018-02-22 11:07 am (UTC)
From: [identity profile] unibasil.livejournal.com
Мне кажется, implementation defined — это универсальный и всегда корректный ответ на любой вопрос в области IT. В других областях человеческой деятельности вместо этого говорят it depends. ;)
Edited Date: 2018-02-22 11:09 am (UTC)

Date: 2018-02-22 11:08 am (UTC)
From: [identity profile] a-konst.livejournal.com
По логике не хватает еще варианта "зависит от стандарта/языка".

Date: 2018-02-22 11:11 am (UTC)
From: [identity profile] avva.livejournal.com
В принципе да, но по-моему в данном случае начиная как минимум с C89 и C++98 разницы нет. Возможно и раньше.

Date: 2018-02-22 11:21 am (UTC)
From: (Anonymous)
Я так думаю, после гугления, что правильный ответ - implementation defined, потому что prvalues of small integral types (such as char) **may** be converted to prvalues of larger integral types (such as int).

http://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion

Date: 2018-02-22 11:22 am (UTC)
From: [identity profile] mopexod.livejournal.com
Integral Promotions
The difference between the ANSI C and traditional versions of the conversion rules is that the traditional C rules emphasize preservation of the (un)signedness of a quantity, while ANSI C rules emphasize preservation of its value.

In traditional C, operands of types char, unsigned char, and unsigned short are converted to unsigned int. Operands of types signed char and short are converted to int.

ANSI C converts all char and short operands, whether signed or unsigned, to int. Only operands of type unsigned int , unsigned long, and unsigned long long may remain unsigned.

Мило.

Date: 2018-02-22 11:22 am (UTC)
From: (Anonymous)
да, какое счастье, что мне как быдло-vb.net-программисту не нужно про это думать.

Date: 2018-02-22 11:23 am (UTC)
livelight: (Default)
From: [personal profile] livelight
Правильно: "IT depends"!

Date: 2018-02-22 11:25 am (UTC)
vladimir000: (Default)
From: [personal profile] vladimir000
Это в предположении, что int != short. Если int == short, то получим unsigned int, иначе - Int.

И не говорите, что 16-битных приложений не бывает:)

Date: 2018-02-22 11:25 am (UTC)
From: [identity profile] aosypov.livejournal.com
Вот я так и подозревал. Сам с Перла, мне можно ;)

Date: 2018-02-22 11:27 am (UTC)
From: [identity profile] mopexod.livejournal.com
Ну, так вообще супер.

Date: 2018-02-22 11:33 am (UTC)
From: [identity profile] unibasil.livejournal.com
Case-sensitive, согласен.

Date: 2018-02-22 11:46 am (UTC)
From: [identity profile] victor-chapaev.livejournal.com
Набираю:

unsigned short foo;
foo= 33000;
short a= foo+foo;

В инспекторе вижу:

foo,x: 0x80E8
foo+foo,x: 0x101D0
a: 464
foo: 33000
foo+foo: 66000

Получается, беззнаковое...

Date: 2018-02-22 11:51 am (UTC)
livelight: (Default)
From: [personal profile] livelight
Интересно, если сложить case insensitive short + case insensitive short, то будет ли результат case sensitive?

Date: 2018-02-22 12:01 pm (UTC)
From: [identity profile] leonov.livejournal.com
Integral promotions и integral conversions проводятся не по желанию левой пятки компилятора, а лишь если результат выражения необходимо использовать в ситуации, требующей другой тип. Т.е. в данном случае - если результат нужно было бы передать функции f(int). Или если бы результат участвовал в арифметическом выражении с операндом другого типа.

Так что висящее в воздухе выражение foo + foo все-таки имеет тип unsigned short.

Date: 2018-02-22 12:01 pm (UTC)
From: [identity profile] mtyukanov.livejournal.com
Ответил implementation defined, но настоящий ответ -- expressions do not really have types.
From: [identity profile] baramin.livejournal.com
Image
Edited Date: 2018-02-22 12:13 pm (UTC)

Date: 2018-02-22 12:13 pm (UTC)
From: [identity profile] avva.livejournal.com
Нет, это у вас знаковый int.

Date: 2018-02-22 12:14 pm (UTC)
From: [identity profile] avva.livejournal.com
Нет, по стандарту они переводятся при любой арифметической операции, вне зависимости от того, что будет происходить с ее результатом.

Date: 2018-02-22 12:14 pm (UTC)
From: [identity profile] avva.livejournal.com
Ага, и поэтому правильный ответ - implementation defined.

Date: 2018-02-22 12:16 pm (UTC)
kuzh: (Default)
From: [personal profile] kuzh
Правильный ответ: не имеет значения.
ПС: а программистом хорошо бы озаботится качеством своих программ, а не забивать голову схоластикой
Edited Date: 2018-02-22 12:45 pm (UTC)

Date: 2018-02-22 12:20 pm (UTC)
From: [identity profile] leonov.livejournal.com
Лишь в случае операндов разного типа. Иначе не имело бы смысл различие в реализации переполнения для знаковых и беззнаковых типов:

Overflows
Unsigned integer arithmetic is always performed modulo 2^n where n is the number of bits in that particular integer. E.g. for unsigned int, adding one to UINT_MAX gives ​0​, and subtracting one from ​0​ gives UINT_MAX.
When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined: it may wrap around according to the rules of the representation (typically 2's complement), it may trap on some platforms or due to compiler options (e.g. -ftrapv in GCC and Clang), or may be completely optimized out by the compiler.

http://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions
Edited Date: 2018-02-22 12:27 pm (UTC)

Conversion rules

Date: 2018-02-22 12:44 pm (UTC)
From: [identity profile] son-0f-morning.livejournal.com
Всегда считал, что инкремент\декремент не требуют правил конвертации.

Но похоже это не так. ОМГ какая клоака прикрыта обычной унарной операцией "++"
Up
Хотя рано паниковать -- ведь в дополнительном коде битовые представления эквивалентны...



ПС
По вопросу:
1. Если sizeof(short) < sizeof(int) => foo+foo signed int
2. Если sizeof(short) == sizeof(int) => foo+foo unsigned int
Edited Date: 2018-02-22 12:48 pm (UTC)
Page 1 of 3 << [1] [2] [3] >>

January 2026

S M T W T F S
    1 23
45678910
11121314151617
18192021222324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 2nd, 2026 05:55 pm
Powered by Dreamwidth Studios