Jump to content
  • Advertisement
Sign in to follow this  
Chrono1081

Char question....

This topic is 3888 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 was wondering why its bad to use char? (I remember seeing this in Zhalmens signature). Also is "using namespace std;" not a good idea too? I often see people use std::cout on here. I am new to C++ and want to break any bad habits at the beginning so any explanation would be greatly appreciated :D

Share this post


Link to post
Share on other sites
Advertisement
The type 'char' is fine.

The problem comes when you try to use arrays of characters manually to simulate text strings. There are two ways to use them, fixed length arrays and dynamically allocated arrays. With fixed length arrays, you have problems because what happens if the user needs to enter more text than you have given them space for? On the other hand, if all the strings they use are short then you are wasting memory. In addition, you have to be careful not to return a fixed length array from a function.

For dynamic arrays, we're in a better position because we don't have an arbitrary upper boundary. But now we get additional problems. Who owns the pointer to the string? When should I make a deep copy? When should it be deallocated? There are additional problems if we forget to deallocate - our program may crash if run over a long period of time as it consumes and leaks memory.

std::string wraps a dynamic character array in a class which implements sensible copy semantics. This means you can pass them to and return them from functions just fine, and it acts how one expects (pass by value is* a deep copy, pass by (const) reference is cheap). It always cleans up after itself. In other words, it Just WorksTM

using namespace in a header file is a bad idea because it causes namespace pollution. A file including that header has no way of "un-using" the namespace. This isn't a problem in personal code, but working in a team or when programming a library it is a bad idea.


* or acts like a deep copy, for COW strings. These are losing popularity due to multi threading concerns AFAIK.

Share this post


Link to post
Share on other sites
Thank you for the explanation! I always thought it was a preference but I can see now that it is not. Anyone else have any juicy pointers that may be helpful to a beginner?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!