简体   繁体   English

G ++ 4.4“未初始化”变量

[英]G++ 4.4 “uninitialized” variables

I am using g++ on Ubuntu 10.10(64-bit) if the OS is at all relevant for the matter. 如果操作系统与此有关,我在Ubuntu 10.10(64位)上使用g ++。 I saw something strange so i decided to check and for some reason this code 我看到一些奇怪的东西所以我决定检查并出于某种原因这段代码

#include <iostream>

int main()
{
    int a;

    std::cout << a << std::endl;

    return 0;
}

always prints 0. Obviously g++ does auto initialization of uninitialized variables to their corresponding null-value. 总是打印0.显然,g ++会将未初始化的变量自动初始化为相应的空值。 The thing is I want to turn that feature off, or at least make g++ show warning about using uninitialized variables, since this way my code won't work well when compiled on VS for instance. 问题是我想关掉这个功能,或者至少让g ++显示关于使用未初始化变量的警告,因为这样我的代码在VS上编译时效果不好。 Besides I'm pretty sure the C++ standard states that a variable which isn't implicitly initialized with some value has an undefined value amongst all it's possible values, which should in fact be different with every execution of the program, since different parts of the operating memory are used every time it's executed. 除此之外,我很确定C ++标准规定一个未用某个值隐式初始化的变量在所有可能的值中都有一个未定义的值,实际上每次执行程序时都应该是不同的,因为不同的部分每次执行时都会使用操作内存。

Explicit question: Is there a way to make g++ show warnings for uninitialized variables? 明确的问题:有没有办法让g ++显示未初始化变量的警告?

GCC does not initialize uninitialized variables to 0. It's just a case that a is 0 . GCC不会将未初始化的变量初始化为0.这只是a0

If what you want to do is to receive warnings when you use uninitialized variables you could use GCC option -Wuninitialized (also included by -Wall ). 如果你想要做的是在使用未初始化的变量时收到警告,你可以使用GCC选项-Wuninitialized (也包括在-Wall )。

However it can't statically spot any possible usage of uninitialized variables: you'll need some run time tools to spot that, and there's valgrind for this. 但是它无法静态发现未初始化变量的任何可能用法:你需要一些运行时工具来发现它,并且有这样的valgrind

You might also try to use a tool like cppcheck . 您也可以尝试使用cppcheck之类的工具。 In general, in well written C++ there is rarely a reason to declare a variable without initializing it. 通常,在编写良好的C ++中,很少有理由在不初始化的情况下声明变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM