我知道这是未定义的:
uint32_t u = 1;
u << 32;
Run Code Online (Sandbox Code Playgroud)
但我对哪种类型的转变未定义感到有些困惑.
是否未定义将有符号整数按其大小(以位为单位)或更多向右移位?
更新:正如答案中所指出的,这是以位为单位的大小,而不是以字节为单位.
我想进入SIZE_MAX
C89.
我想到了以下方法SIZE_MAX
:
const size_t SIZE_MAX = -1;
Run Code Online (Sandbox Code Playgroud)
由于标准(§6.2.1.2ANSIC)说:
当有符号整数转换为具有相等或更大大小的无符号整数时,如果有符号整数的值为非负,则其值不变.否则:如果无符号整数的大小更大,则有符号整数首先被提升为与无符号整数对应的有符号整数; 通过向该值添加一个大于可以在无符号整数类型 28中表示的最大数字的值,将该值转换为无符号
脚注28:
在二进制补码表示中,如果无符号整数具有更大的大小,则除了用符号位的副本填充高位以外,位模式中没有实际的变化.
这似乎已经定义了行为,但我不太确定我是否正确理解了该段落的措辞.
请注意,这个问题明确是关于C89的,所以这不能回答我的问题,因为标准有不同的措辞.
如果这不起作用,我提出的另一种方式是:
size_t get_size_max() {
static size_t max = 0;
if (max == 0) {
max -= 1U;
}
return max;
}
Run Code Online (Sandbox Code Playgroud)
但我在标准中找不到任何关于无符号整数下溢的信息,所以我在这里瞎了.
我想创建一个模板,其中包含一个应该保持未构造的私有成员,直到使用placement new显式构造它.
如何用C++ 14实现这一目标?
有点像这样:
template <typename T>
class Container {
private:
T member; //should be left unconstructed until construct() is called
public:
Container() = default;
void construct() {
new (&this->member) T();
}
};
Run Code Online (Sandbox Code Playgroud) 我即将学习bash脚本并编写一个这样的小脚本用于测试目的:
#!/bin/bash
function time {
echo $(date)
}
time
Run Code Online (Sandbox Code Playgroud)
However the function doesn't get executed, instead the command time
is running.
So what do I have to do to execute the function instead?
I'm running bash 4.2.45
我正在为gcc搜索编译器标志,如果可能的话,还要为clang和Microsoft编译器搜索,-Werror
如果在不使用返回值的情况下调用非void函数,则触发警告(错误):
int test() {
return 4;
}
int main(void) {
test(); //should trigger a warning
int number = test(); //shouldn't trigger the warning
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果没有这样的编译器标志,也许某种方式告诉clang静态分析器抱怨它.
编辑:澄清我原来的问题:我实际上是指使用返回值,而不仅仅是分配它.
我已经编写了一些代码字段的代码,我认为应该可行,但看起来像GCC不同意.我是否错过了某些内容或者我是否真的在GCC中发现了一个错误?
简化我的代码后,测试用例非常简单.我将整数文字分配给1
一个大小为一位的位域:
typedef struct bitfield
{
int bit : 1;
} bitfield;
bitfield test()
{
bitfield field = {1};
return field;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用GCC 6.2.1(与5.4.0相同)编译它,我会收到以下警告(使用-pedantic):
gcc -fPIC test.c -pedantic -shared
test.c: In function ‘test’:
test.c:8:23: warning: overflow in implicit constant conversion [-Woverflow]
bitfield field = {1};
^
Run Code Online (Sandbox Code Playgroud)
奇怪的是:当我用-Woverflow替换-pedantic时,警告消失了.
我没有得到任何警告警告.