реклама на сайте
подробности

 
 
> Деление int на size_t
sonycman
сообщение Nov 6 2013, 10:37
Сообщение #1


Любитель
*****

Группа: Свой
Сообщений: 1 864
Регистрация: 20-08-06
Из: Тольятти
Пользователь №: 19 695



Возникла непонятка.
Использую деление переменной типа int на значение, возвращаемое функцией sizeof():

int t;
...
t = t / sizeof(buf);
if (t < 0) ...
else ...

Так вот - знак t может быть различный, но после деления на sizeof() компилятор считает, что знак результата становится положительный и отбрасывает ветку кода для обработки отрицательного значения. Даже функция деления используется беззнаковая.
Если вместо sizeof() подставить константу, то всё начинает работать как положено.

Что я делаю не так, подскажите?
Go to the top of the page
 
+Quote Post
 
Start new topic
Ответов
Genadi Zawidowsk...
сообщение Jan 5 2014, 00:20
Сообщение #2


Профессионал
*****

Группа: Участник
Сообщений: 1 620
Регистрация: 22-06-07
Из: Санкт-Петербург, Россия
Пользователь №: 28 634



Ну написано же в стандарте явно про беззнаковость size_t...
Цитата
3.3.3.4 The sizeof operator

Constraints

The sizeof operator shall not be applied to an expression that has
function type or an incomplete type, to the parenthesized name of such
a type, or to an lvalue that designates a bit-field object.

Semantics

The sizeof operator yields the size (in bytes) of its operand,
which may be an expression or the parenthesized name of a type. The
size is determined from the type of the operand, which is not itself
evaluated. The result is an integer constant.

When applied to an operand that has type char , unsigned char , or
signed char , (or a qualified version thereof) the result is 1. When
applied to an operand that has array type, the result is the total
number of bytes in the array./35/ When applied to an operand that has
structure or union type, the result is the total number of bytes in
such an object, including internal and trailing padding.

The value of the result is implementation-defined, and its type (an
unsigned integral type) is size_t defined in the <stddef.h> header.



И про преобразование перед делением:
Цитата
3.2.1.5 Usual arithmetic conversions

Many binary operators that expect operands of arithmetic type cause
conversions and yield result types in a similar way. The purpose is
to yield a common type, which is also the type of the result. This
pattern is called the usual arithmetic conversions: First, if either
operand has type long double, the other operand is converted to long
double . Otherwise, if either operand has type double, the other
operand is converted to double. Otherwise, if either operand has
type float, the other operand is converted to float. Otherwise, the
integral promotions are performed on both operands. Then the
following rules are applied: If either operand has type unsigned long
int, the other operand is converted to unsigned long int.
Otherwise, if one operand has type long int and the other has type
unsigned int, if a long int can represent all values of an unsigned
int, the operand of type unsigned int is converted to long int ; if a
long int cannot represent all the values of an unsigned int, both
operands are converted to unsigned long int. Otherwise, if either
operand has type long int, the other operand is converted to long int.
Otherwise, if either operand has type unsigned int, the other
operand is converted to unsigned int. Otherwise, both operands have
type int.

The values of operands and of the results of expressions may be
represented in greater precision and range than that required by the
type; the types are not changed thereby.


Сообщение отредактировал Genadi Zawidowski - Jan 5 2014, 00:21
Go to the top of the page
 
+Quote Post

Сообщений в этой теме
- sonycman   Деление int на size_t   Nov 6 2013, 10:37
- - Xenia   Цитата(sonycman @ Nov 6 2013, 14:37) int ...   Nov 6 2013, 11:24
|- - sonycman   Цитата(Xenia @ Nov 6 2013, 15:24) Результ...   Nov 6 2013, 13:25
||- - defunct   Цитата(sonycman @ Nov 6 2013, 15:25) Но р...   Dec 24 2013, 17:18
|- - mdmitry   Цитата(Xenia @ Nov 6 2013, 15:24) Результ...   Nov 6 2013, 14:20
|- - Xenia   Цитата(mdmitry @ Nov 6 2013, 18:20) А не ...   Nov 6 2013, 16:43
- - V_G   Если перейдете на С++ (язык с более строгим контро...   Nov 6 2013, 14:00
- - sonycman   Программа и так компилируется в плюсах, какого-то ...   Nov 6 2013, 15:11
|- - zhevak   Цитата(sonycman @ Nov 6 2013, 21:11) Прог...   Nov 6 2013, 16:47
|- - AHTOXA   Цитата(sonycman @ Nov 6 2013, 21:11) Прог...   Nov 6 2013, 16:59
|- - sonycman   Цитата(V_G @ Nov 6 2013, 18:00) Если пере...   Nov 6 2013, 22:38
|- - V_G   Цитата(sonycman @ Nov 7 2013, 08:38) Это ...   Nov 7 2013, 00:44
|- - AHTOXA   Цитата(sonycman @ Nov 7 2013, 04:38) А во...   Nov 7 2013, 03:59
|- - zhevak   ... и еще вот тут есть интересные рассуждения про ...   Nov 7 2013, 06:09
|- - sonycman   Цитата(AHTOXA @ Nov 7 2013, 07:59) Ваш ва...   Nov 7 2013, 08:47
|- - AHTOXA   Цитата(sonycman @ Nov 7 2013, 14:47) Веро...   Nov 7 2013, 09:30
|- - sonycman   Цитата(AHTOXA @ Nov 7 2013, 13:30) 1. siz...   Nov 7 2013, 09:37
|- - AHTOXA   Вот уж не ожидал, что приведённое мной объяснение ...   Nov 7 2013, 11:17
|- - sonycman   Цитата(AHTOXA @ Nov 7 2013, 15:17) Вот уж...   Nov 7 2013, 12:27
|- - AHTOXA   Это не мой стандарт, это стандарт языка Си. И лучш...   Nov 7 2013, 16:33
|- - sonycman   Цитата(AHTOXA @ Nov 7 2013, 20:33) (И пос...   Nov 7 2013, 21:31
|- - AHTOXA   Цитата(sonycman @ Nov 8 2013, 03:31) Оба ...   Nov 8 2013, 04:17
- - sonycman   Прошу прощения, поторопился я вчера с выводами, по...   Nov 8 2013, 10:19
|- - zhevak   Да. Было бы любопытно посмотреть на распечатку асс...   Nov 8 2013, 11:29
|- - sonycman   Цитата(zhevak @ Nov 8 2013, 15:29) Да. Бы...   Nov 8 2013, 12:02
|- - zhevak   Цитата(sonycman @ Nov 8 2013, 18:02) Вы п...   Nov 8 2013, 13:39
- - sonycman   Без проблем, только я сейчас на работе, и смогу до...   Nov 8 2013, 14:13
- - ILYAUL   Коллеги , а давайте в отдельной теме. Эта всё таки...   Nov 8 2013, 14:13
|- - IgorKossak   Цитата(ILYAUL @ Nov 8 2013, 16:13) Коллег...   Nov 8 2013, 18:33
- - sonycman   Несколько устав уже от нюансов по поводу интерпрет...   Nov 9 2013, 19:56
|- - maksimp   Цитата(sonycman @ Nov 9 2013, 22:56) При ...   Nov 28 2013, 20:35


Reply to this topicStart new topic
1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0

 


RSS Текстовая версия Сейчас: 5th August 2025 - 19:16
Рейтинг@Mail.ru


Страница сгенерированна за 0.0141 секунд с 7
ELECTRONIX ©2004-2016