Adsense

p[lacehoder
placehoolder

Monday, January 10, 2011

The Most Common Mistake in C++ Programming

                After programming c++ for several years, i still make common mistakes that costs alot of time and stress.  Nevertheless, due to my experience, it is easy for me to figure out what this problem is most of the time.   For others who are just beginning c++, they can not afford of luxury of experience, thus they struggle for hours or days to try to find out the error.   Based on my days as a new programmer and on the experiences of several other beginner programmers, the most common but most catastrophic error is not having a return value for non-void functions.

                Most often, people will write functions that have a return value or int or string but in their code body, they do not return anything or sometimes just type “return”:

i.e
int me()
{…….
Return;
}
                This is fatal because even if you do not specify a return value, c++ will automatically and randomly return something of the specified return type.   Now, many people do this and with returns types like ints or floats, errors rarely occur, however, if you specify a function that returns a string and you do not return anything, you will get a lot of undefined errors or most of the time, you will get a seg fault.
http://en.wikipedia.org/wiki/Segmentation_fault
The reason is that a string is basically a array of character, one points to the next, and they take up a chunk of space of main memory.  Now, since you did not specify what string to return, the compiler will automatically return a string of arbitrary size and from and arbitrary location, now due to this randomized event, the compiler might choose a part in memory that is currently being allocated to another program, or event worse, a vital system service.  Thus, the OS intervenes, stops your program, and you get a seg fault.

                So the main theme here is to always return something, have a return value.  If you want your int function to return nothing, then type:
return 0;
if you want your string function to return nothing, then type :
return  “”;

this returns an empty string.   IF YOUR FUNCTIONS HAS A RETURN TYPE, THEN GIVE IT A RETURN VALUE, OTHERWISE  JUST WRITE A VOID FUNCTION!!
Returning values is a habit that you must get into, especially If you are writing large programs and want to minimize headaches.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...