snippet code 1
#include <iostream>
int main(int argc, char **argv)
{
std::cout << 25u - 50;
return 0;
}
如果是32位的整型,那么结果是4294967271
Tips:如果进行运算的两个item,lower type将会被转化成为 higher type。类型的高低顺序为: long double, double, float, unsigned long int, long int, unsigned int, int(lowest). 25u - 50便成为 25u - 50u
In C++, if the types of two operands differ from one another, then the operand with the “lower type” will be promoted to the type of the “higher type” operand, using the following type hierarchy (listed here from highest type to lowest type): long double, double, float, unsigned long int, long int, unsigned int, int (lowest). Moreover, the result of the operation will be of the type of the operands. Therefore, the result of
25u - 50u
will itself be an unsigned integer as well. So the result of-25
converts to 4294967271 when promoted to being an unsigned integer.
snippet code 2
my_struct_t *bar;
/*... do stuff, including setting bar to point to a defined my_struct_t object ... */
memset(bar, 0, sizeof(bar));
在这里sizeof(bar)计算的是指针bar本身的大小,应该使用的是sizeof(*bar), 如果bar是野指针,那么可以引起 dereferencing error
, 因此最安全的方法还是使用 sizeof(my_struct_t)
The last argument to
memset
should besizeof(*bar)
, notsizeof(bar)
.sizeof(bar)
calculates the size ofbar
(i.e., the pointer itself) rather than the size of the structure pointed to bybar
. The code can therefore be corrected by usingsizeof(*bar)
as the last argument in the call tomemset
. A sharp candidate might point out that using*bar
will cause a dereferencing error ifbar
has not been assigned. Therefore an even safer solution would be to usesizeof(my_struct_t)
. However, an even sharper candidate must know that in this case using*bar
is absolutely safe within the call tosizeof
, even ifbar
has not been initialized yet, sincesizeof
is a compile time construct.
snippet code 3
size_t sz = buf->size();
while (--sz >= 0)
{
/* do something */
}
以上的代码可能会无限的循环知道内存 corrupting
,这是因为size_t其实是与机器相关的unsigned integer的引用,因此sz不可能为负。以上的片段可以用如下代码来替代
The problem in the above code is that
--sz >= 0
will always be true so you’ll never exit thewhile
loop (so you’ll probably end up corrupting memory or causing some sort of memory violation or having some other program failure, depending on what you’re doing inside the loop).The reasons that
--sz >= 0
will always be true is that the type ofsz
issize_t
.size_t
is really just an alias to one of the fundamental unsigned integer types. Therefore, sincesz
is unsigned, it can never be less than zero (so the condition can never be true).
for (size_t i = 0; i < sz; i++)
{
/* do something */
}
snippet code 4
option1
vector vec;
/*.......*/
for(auto itr = vec.begin(); itr != vec.end(); itr++) {
itr->print();
}
option2
vector vec;
/*.......*/
for (auto itr = vec.begin(); itr != vec.end(); ++itr) {
itr->print();
}
option2优于option1,这是因为itr++比++itr更加的耗费资源。当然,很多编译器会自动把第一种优化成为第二种。