Skip to content

Instantly share code, notes, and snippets.

@kwatch
Last active February 16, 2016 05:24
Show Gist options
  • Save kwatch/f34bf0bb275cdbb37050 to your computer and use it in GitHub Desktop.
Save kwatch/f34bf0bb275cdbb37050 to your computer and use it in GitHub Desktop.
C++ compiler warns uninitialized local variable of int, but not of object.
#include <iostream>
#include <string>
void fn() {
int x;
std::string s;
std::cout << x; // warning: variable 'x' is uninitialized when used here
std::cout << s; // (no warnings due to default constructor)
std::cout << "\n";
}
int main(void) {
fn();
return 0;
}
/****
$ g++ -Wall ex2.cpp
ex2.cpp:7:18: warning: variable 'x' is uninitialized when used here
[-Wuninitialized]
std::cout << x; // warning: variable 'x' is uninitialized when used here
^
ex2.cpp:5:10: note: initialize the variable 'x' to silence this warning
int x;
^
= 0
1 warning generated.
$ ./a.out
32767
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.3.0
Thread model: posix
****/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment