Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it that an int in C++ that isnt initialized (then used) doesn't return an error?

I am new to C++ (just starting). I come from a Java background and I was trying out the following piece of code that would sum the numbers between 1 and 10 (inclusive) and then print out the sum:

/* 
 * File:   main.cpp
 * Author: omarestrella
 *
 * Created on June 7, 2010, 8:02 PM
 */

#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
    int sum;

    for(int x = 1; x <= 10; x++) {
        sum += x;
    }

    cout << "The sum is: " << sum << endl;

    return 0;
}

When I ran it it kept printing 32822 for the sum. I knew the answer was supposed to be 55 and realized that its print the max value for a short (32767) plus 55. Changing

int sum;

to

int sum = 0;

would work (as it should, since the variable needs to be initialized!). Why does this behavior happen, though? Why doesnt the compiler warn you about something like this? I know Java screams at you when something isnt initialized.

Thank you.

Edit: Im using g++. Here is the output from g++ --version: Im on Mac OS X and am using g++.

nom24837c:~ omarestrella$ g++ --version
i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646)
like image 688
Omar Estrella Avatar asked Nov 27 '22 22:11

Omar Estrella


2 Answers

Reading from an uninitialized variable results in undefined behavior and the compiler isn't required to diagnose the error.

Note that most modern compilers will warn you if you attempt to read an uninitialized variable. With gcc you can use the -Wuninitialized flag to enable that warning; Visual C++ will warn even at warning level 1.

like image 61
James McNellis Avatar answered Nov 29 '22 11:11

James McNellis


Because it's not part of the C++ standard. The variable will just take whatever value is currently sitting in the memory it's assigned. This saves operations which can sometimes be unnecessary because the variable will be assigned a value later.

It's interesting to note and very important for Java/.Net programmers to note when switching to C/C++. A program written in C++ is native and machine-level. It is not running on a VM or a some other sort of framework. It is a collection of raw operations (for the most part). You do not have a virtual machine running in the background checking you variables and catching exceptions or segfaults for you. This is a big difference which can lead to a lot of confusion in the way C++ handles variables and memory, as opposed to Java or a .Net language. Hell, in .Net all your integers are implicitly initialised to 0!

like image 28
Anthony Avatar answered Nov 29 '22 12:11

Anthony