blog

10 Things Your Competitors Can Teach You About c++ check if string is empty

The most common mistake that programmers make, and this is for good reason, is checking if a string is empty. This is also one of the reasons why it is so important to always check for nullptr in your code.

A C++ programmer wrote about this in his book called “Effective C++”. It says that the best way to ensure that a string is not empty is to check if it contains any non-NULL characters.

We should be checking for NULLs, not non-NULLs, and string.operator[](int) is an example of a code that would be a good candidate for being null. But if a code’s length is 0 then that code must be null.

That is exactly what the C standard says, but it’s also true that a valid C program can have 0 length. That is called a null pointer.

That is true, but the C standard also says that if a string is empty, the empty string is a null pointer. So if you have a non-empty string, and you try to access the first character, you’ll get a valid pointer, but you’ll get a null pointer. That is because the string is not empty, and a string is not empty if its not null.

So why is this a problem? Well, let’s assume you have a string that is NOT empty, and you try to access the first character of the string. Youll NOT get a valid pointer, but a null pointer. The null pointer is undefined behavior. If the pointer was set to NULL, you could get a valid pointer, but as a result of that pointer being NULL, you would get a null pointer.

The string is empty because when you try to access the first character of the string, youll get a null pointer because there is no character, and it doesn’t have a character. So in this case, you can’t get a valid pointer, and it’s undefined behavior.

But it DOES help to know that C++ is more verbose than C, which makes it a good idea to learn C first. It can be easier to learn a language by understanding how it works.

But C is a huge language. So it can be pretty messy, for which reason I highly recommend that you learn C first, which will make you a better C programmer in the long run.

Leave a Reply

Your email address will not be published. Required fields are marked *