Archived

This topic is now archived and is closed to further replies.

C++ gripe

This topic is 5043 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m quite new to these forums and the programming in general. I decided to post here with this issue I had today, and see if this has happened to anyone else, or if I''m just careless. =) When you declare a variable in say, Main, for example... if you attempt to use it before assigning it a value, the compiler will give you a warning that says "variable used without being initialized." Yet, it is only a warning not an error... so you can still compile, but at least it alerts you, in case you just forgot a simple assign statement. Now pretend that you have a class with a Private variable called int height. Now you have a member function that you call in your main program. This member function makes use of the height variable. But WOOPS! You forget to call set() which sets the value of height. C++ gives you no error or warning, and you spend 5 hours wondering why your code isn''t working as intended. Is there some reason that the compiler (specifically MSVC++ 7.0 which is what I''m using) does not notice the use of a variable with no assigned value in the class, yet it recognizes it in Main? Thanks

Share this post


Link to post
Share on other sites
The compiler has no way of knowing if set() will always be called before the variable is used since set() can be called from anywhere at any time as far as the compiler knows.

On the other hand, the compiler can see the entire life of a local variable and everything that happens to it. So it can do a reasonable job of checking that it is initialized before it is used.

Share this post


Link to post
Share on other sites