Error Checking in C: Understanding the If Statement Condition

  • Thread starter TheSourceCode
  • Start date
  • Tags
    Error
In summary, the conversation discusses the use of scanf() and its return value in C programming. The code provided uses scanf() to retrieve an integer input and stores it in a variable called snum. The if statement checks if the return value of scanf() is 0, indicating an error in the input, and terminates the program if so. The conversation also discusses the use of ! in front of a non-boolean type and the different ways of handling input errors.
  • #1
TheSourceCode
14
0
I have the following chunk of C code that checks for errors. Works fine but I don't understand why it works.
Code:
printf("\nEnter the number of students\n");
valid_input = scanf("%d", &snum);
if(!valid_input){
   printf("\nInvalid number of students\n");
   system("pause");
   return 1;
}
The condition of the if statement is confusing me. From what I understand it is returning true if valid_input is false then terminates the program with an error code. What makes valid_input false when I type characters in it? Do all variables become false when there is data of the wrong type stored in them?
 
Physics news on Phys.org
  • #2
Return Value

Returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.

http://msdn.microsoft.com/en-us/library/9y6s16x1(v=vs.71).aspx
 
  • #3
There are two things going on. First of all, scanf()'s return value is the number of items that it successfully pulled out of the input string. The format string is "%d", which means "look for an integer", so if you enter something that can be interpreted as an integer, it will put it into snum, and return 1. If you enter something that can't be interpreted as an integer, it returns 0. By extension, if the format string to scanf() was "%d %d", and you entered one number followed by a space and then another number, then scanf() would return 2.

That's part 1. Part 2 is how the if statement works. Normally we think of an if statement as operating on a boolean value, but C doesn't actually have a boolean type. Instead, if() treats its argument as false any time it is 0, and true if it's any other value. The ! causes it to invert that, so the net result is that if the string contains a number, scanf() returns 1, so the if(!valid_input) does not fire. If the string doesn't contain a number, valid_input is 0, so the if statement is triggered, and the program exits with an error.
 
  • #4
scanf() returns the number of fields successfully converted and assigned. It's not an error value. In this case, valid_input = scanf("%d", &snum); scanf returns 1 if a field was converted and assigned to snum, otherwise it returns a 0.

There's no general consistency in the return values from the c or c++ library functions. If the return value from a typical function is not normally used, then the function may return an error value. If the function normally returns a pointer, then returing a pointer of NULL would usually indicate an error, and with windows, you'd have GetLastError(), _get_errno(), or _get_doserrno() to get the error value, depending on the function you called.
 
  • #5
Thanks everyone. I did learn at some point that scanf returns a value but must have forgotten. Makes sense now.
 
  • #6
It's been 3 years since I did any C programming, wish I kept it up. I can still understand most code, although, is valid_input a library defined function? If so, which library?
 
  • #7
NewtonianAlch said:
It's been 3 years since I did any C programming, wish I kept it up. I can still understand most code, although, is valid_input a library defined function? If so, which library?
valid_input is not a function. It is a variable, presumably of type int, in which the return value from scanf() is stored. The function scanf() is a part of the C standard library and returns the number of items that were assigned a value. In this case, there is only one item to be assigned, the number of students, so the function returns 1 indicating a value was parsed, 0 if there was something wrong in the input stream.

I'm not thrilled with the if(!valid_input) scheme. My personal preference is to use ! for booleans only. The return value appears to be boolean in this case, but in general it isn't. I would instead use if (valid_input != 1) to test for input errors. That's just my personal preference, though.
 
  • #8
Yeah, valid_input was an integer variable. And I think the ! in front of the int is what confused me. I had done it another way but this was how the prof did it in his solution. I was just trying to understand why his way worked also.
 
  • #9
I always go back and forth on the issue of whether or not to use ! with non-boolean types. I generally don't use it for ints like this (precisely because it causes this confusion), but I've found myself doing it fairly often for pointer values to check for NULL. I suppose that's a bit ugly as well, but I guess I justify it by saying that the distinction between a NULL pointer and a non-NULL pointer is clearer than the distinction between 0 and 1, since the former feel like different types of things, but the latter are both just ints.

Python, on the other hand, goes nuts with this concept. Since the language is duck-typed, anything that looks sort of empty, like an empty string/list/set/dict, as well as anything that evaluates numerically to 0, is considered false. So you can do things like:

Code:
string = ''
if not string:
   # Will be executed

list = ['asdf']
if list:
   # Will be executed

# ...etc.

It makes for some really convenient code, but sometimes it takes a second to figure out exactly what is actually happening.
 

FAQ: Error Checking in C: Understanding the If Statement Condition

What is the purpose of error checking in C?

The purpose of error checking in C is to ensure that the program runs smoothly and without any unexpected errors. By implementing error checks, the programmer can catch and handle any potential errors or bugs that may occur during the execution of the program.

How does the "if" statement condition work in error checking?

The "if" statement condition is used in error checking to evaluate a specific condition and execute a certain block of code if that condition is met. This allows the programmer to check for errors or invalid inputs and handle them accordingly.

What are some common errors to check for in C programs?

Some common errors to check for in C programs include null pointers, out-of-bounds array access, and division by zero. Additionally, programmers should also check for any potential errors related to user input, file operations, and memory allocation.

How can error checking improve the overall quality of a C program?

Error checking can improve the overall quality of a C program by helping to identify and fix potential errors early on in the development process. By catching and handling errors, the program will be more reliable and less likely to crash or produce unexpected results.

Are there any best practices for implementing error checking in C?

Yes, there are some best practices for implementing error checking in C. These include using specific error codes to identify different types of errors, providing descriptive error messages, and properly handling errors to prevent program crashes. It is also important to regularly test and debug the error checking code to ensure its effectiveness.

Similar threads

Replies
3
Views
1K
Replies
1
Views
10K
Replies
3
Views
930
Replies
4
Views
1K
Replies
21
Views
2K
Replies
5
Views
2K
Replies
1
Views
4K
Back
Top