我有点困惑.据我所知,如果你在C中声明一个int,而不是初始化它,例如:int x;
所以它的价值是不确定的.因此,如果我们尝试使用它或应该有未定义的行为.
所以,如果我在VS2010中运行以下代码,它会导致程序崩溃.
int main(){
int a;
printf("%d\n",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在让我们来看看下一个代码,它没有提供任何警告而且没有崩溃(为什么?)
void foo(int *var_handle){
// do nothing
}
int main(){
int a;
foo(&a);
printf("%d\n",a); // works, prints some big value
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你能解释一下这种行为吗?我们只添加了对一个什么都不做的函数的调用,但现在程序不会崩溃.
我已经阅读了该问题的答案:为什么 c++ 中的 char 和 bool 的大小相同?并做了一个实验来确定内存中分配的字节大小 a_Bool和 a bool(我知道这bool是一个_Boolin的宏,stdbool.h但为了完整起见,我也使用了它)在 C 中的bool对象,以及在我的实现中的 C++ 中的对象Linux Ubuntu 12.4:
对于 C:
#include <stdio.h>
#include <stdbool.h> // for "bool" macro.
int main()
{
_Bool bin1 = 1;
bool bin2 = 1; // just for the sake of completeness; bool is a macro for _Bool.
printf("the size of bin1 in bytes is: %lu \n",(sizeof(bin1)));
printf("the size of bin2 in bytes is: %lu …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
#include <stdio.h>
int main()
{
char A = A ? 0[&A] & !A : A^A;
putchar(A);
}
Run Code Online (Sandbox Code Playgroud)
我想问一下,是否观察到任何未定义的行为.
编辑
请注意:代码故意使用0[&A] & !A和NOT A & !A(请参阅下面的回复)
结束编辑
从g ++ 6.3(https://godbolt.org/g/4db6uO)获取输出ASM 得到(没有使用优化):
main:
push rbp
mov rbp, rsp
sub rsp, 16
mov BYTE PTR [rbp-1], 0
movzx eax, BYTE PTR [rbp-1]
movsx eax, al
mov edi, eax
call putchar
mov eax, 0
leave
ret
Run Code Online (Sandbox Code Playgroud)
然而clang为同一件事提供了更多的代码(没有再次优化):
main: # @main
push rbp
mov rbp, rsp
sub rsp, 16 …Run Code Online (Sandbox Code Playgroud) 考虑这段代码
T* pa = new T(13);
int address = reinterpret_cast<int>(pa);
Run Code Online (Sandbox Code Playgroud)
其中T可以是任何内置类型.
1)我无法理解重新诠释这里有什么问题?
2)这种铸件会导致不确定的行为的情况是什么?
3)将pa始终包含内存地址的正确十进制表示?
是否存在与 Python 类型等效的 C 数据类型None?
我试图在互联网上搜索它,但我找不到任何东西。
谢谢你,
我遇到了这样的C++测验:如果指针被删除两次会发生什么?
答案是D.
我有点失落,"陷阱"是什么意思?它是C++中的一个特殊术语吗?
当我打印b并且d他们都持有相同的地址(地址a).那么为什么*b打印0和*d打印5?
void main()
{
double a = 5.0;
double *d = &a;
int *b = (int*)d;
int a1 = 10;
cout << "Val of D : " << d << " Address of d :" << &d
<< " Value of *d :" << *d << endl;
cout << "Val of B : " << b << " Address of B :" << &b
<< " Value of …Run Code Online (Sandbox Code Playgroud) #include <stdio.h>
int main()
{
int i,j=3;
i=4+2*j/i-1;
printf("%d",i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它会每次打印9,虽然我没有初始化,所以,它必须打印任何垃圾值.请解释...