A variable cannot be "empty." It always has a value.
You can manually specify a value, which indicates "emptiness" as done with strings: a null byte (with the value 0) indicates the end of the string. Here, it's not emptiness per se but you get what I mean, hopefully.
Because a variable cannot be empty, there is no common NaN value for it; every value is a number, so NaN (not a number) does not make sense.
The floating-point format IEEE 754 supports NaN values but that is only possible because certain values of floating-point numbers have been assigned that meaning.
A variable cannot be "empty." It always has a value.
You can manually specify a value, which indicates "emptiness" as done with strings: a null byte (with the value 0) indicates the end of the string. Here, it's not emptiness per se but you get what I mean, hopefully.
Because a variable cannot be empty, there is no common NaN value for it; every value is a number, so NaN (not a number) does not make sense.
The floating-point format IEEE 754 supports NaN values but that is only possible because certain values of floating-point numbers have been assigned that meaning.
A variable resides in RAM. RAM is never empty. Each cell has a value. Either the value is known by the programmer or not, depends whether the programmer has initialized that variable or not.
I know two ways of signaling the "emptyness" of a variable. One is to have a value that means "empty", like "0", or MAX_INTEGER, or whatever you like. This works if the logic of your algorithm imposes your variable to have only certain values, so you can know when the value is valid or not. If not, you can say the variable is not valid, or empty.
If your variable can hold any value (within the limits of your type), then a solution may be to use a small struct, like this:
typedef struct
{
int value;
int is_empty;
} tVar;
So declaring variable i this way...
tVar i;
You can initialize as empty, like this:
i.is_empty = 1;
So, your program becomes:
int main( void )
{
tVar someVar = {0,1}; // declaring and initializing it as empty
...
...
...
if (!someVar.is_empty) // if someVar is not empty...
{
someVar.value = -1;
someVar.is_empty = 0; // is not empty any more
}
else if (someVar.is_empty && (some_other_condition))
{
someVar.value = 1;
someVar.is_empty = 0;
}
return 0;
}
I need a bit of help with coding in C/C++. Right now Im working ahead on assignments since its been a slow week for me. I have to create a function that allows the user to input information to a structure within an array for a database of customers. The requirements is that all of the "fields" where the information needs to be entered have to be filled up. So you cant put in name, balance, and address, and leave the last several fields empty. This means that I am dealing with string, int, and double types of information. So far I have:
while (x==0)
{
cust.customer_number = num_of_cust;
cout << "Enter new customer name: ";
cin >> cust.name;
cout << "Enter new customer phone: ";
cin >> cust.phone_number;
cout << "Enter new customer street sddress: ";
cin >> cust.street_address.street;
cout << "Enter new customer city: ";
cin >> cust.street_address.city;
cout << "Enter new customer state: ";
cin >> cust.street_address.state;
cout << "Enter new customer zip code: ";
cin >> cust.street_address.zip_code;
cout << "Enter new customer balance: $";
cin >> cust.balance;
cout << "Enter new customers last payment date: ";
cin >> cust.payment_date;
}I will break the while loop by including an if statement at the end so that if everything is filled in it will increment x to be 1 which would then violate the while condition and break it out of the loop. so something like:
if(cust.name==blank||cust.phone_number==blank||...)
{
x=1;
}Where I replace the blanks with whatever term I need to indicate an empty variable.
Change:
char *filename;
To:
char *filename = NULL;
Then your NULL tests will work.
When you don't initialize this pointer, its value is undefined. That's why your tests were failing. The compiler assumed that you didn't care what value it had.
You must initialize the pointer yourself, it doesn't have a guaranteed starting value otherwise.
char *filename = NULL;
Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing
do {
...
} while (url[0] != '\0');
Alternatively, you could use the strcmp function, which is overkill but might be easier to read:
do {
...
} while (strcmp(url, ""));
Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is empty.
Hope this helps!
If you want to check if a string is empty:
if (str[0] == '\0')
{
// your code here
}
In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).
A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):
void fill_foo(int* foo) {
*foo = 23; // this will crash and burn if foo is NULL
}
A better version:
void fill_foo(int* foo) {
if (!foo) { // this is the NULL check
printf("This is wrong\n");
return;
}
*foo = 23;
}
Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.
The other answers pretty much covered your exact question. A null check is made to be sure that the pointer you received actually points to a valid instance of a type (objects, primitives, etc).
I'm going to add my own piece of advice here, though. Avoid null checks. :) Null checks (and other forms of Defensive Programming) clutter code up, and actually make it more error prone than other error-handling techniques.
My favorite technique when it comes to object pointers is to use the Null Object pattern. That means returning a (pointer - or even better, reference to an) empty array or list instead of null, or returning an empty string ("") instead of null, or even the string "0" (or something equivalent to "nothing" in the context) where you expect it to be parsed to an integer.
As a bonus, here's a little something you might not have known about the null pointer, which was (first formally) implemented by C.A.R. Hoare for the Algol W language in 1965.
I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
The behavior of isInteger should be defined (or explicitly undefined) for any inputs. It's not unreasonable to leave the behavior of isInteger(NULL) undefined, requiring the caller to pass a valid string pointer.
As unwind's answer suggests, isInteger should probably return false (0) for an empty string.
But if you want to check for an empty string yourself, you can check for a length of 0:
char *aux;
aux=getenv("MAX_OUTPUT");
if (aux==NULL || strlen(aux) == 0 || !(isInteger(aux))){
/*code*/
}
Or, equivalently, you can check whether the first (0th) character of the string is the terminating null '\0' character:
char *aux;
aux=getenv("MAX_OUTPUT");
if (aux==NULL || *aux == '\0' || !(isInteger(aux))){
/*code*/
}
*aux can also be written as aux[0].
Note that this doesn't check for, for example, aux containing a single blank: " ", but again, isInteger should probably handle that.
Assuming that isInteger behaves reasonably, returning a true result for any string that looks like an integer and a false result for any string that doesn't (and perhaps with undefined behavior for a null pointer or a pointer that doesn't point to a valid string), then this:
if (aux == NULL || !isInteger(aux)) {
/* it's not an integer */
}
should be sufficient.
If isInteger() doesn't say false for an empty string, I would hesitate to claim that it works. Of course, without the code for isInteger() included, it's hard to be more specific.
I think a function like bool isInteger(const char *str) must return false for both NULL and an empty string, so the aux == NULL test should not even be needed.
Check if the first character is '\0'. You should also probably check if your pointer is NULL.
Copychar *c = "";
if ((c != NULL) && (c[0] == '\0')) {
printf("c is empty\n");
}
You could put both of those checks in a function to make it convenient and easy to reuse.
Edit: In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not '\0' or zero, then...".
The && simply combines the two conditions. It is basically like saying this:
Copyif (c != NULL) { /* AND (or &&) */
if (c[0] == '\0') {
printf("c is empty\n");
}
}
You may want to get a good C programming book if that is not clear to you. I could recommend a book called "The C Programming Language".
The shortest version equivalent to the above would be:
Copyif (c && !c[0]) {
printf("c is empty\n");
}
My preferred method:
Copyif (*ptr == 0) // empty string
Probably more common:
Copyif (strlen(ptr) == 0) // empty string