function returning optional value - c

Whenever we call a function returning value why it is not required to catch the value?
consider the following C code,
int main()
{
int i;
scanf("%d",&i);
printf("Value of i is: ",i);
return 0;
}
Here scanf() returns value 1, but as it is not catched in anywhere why didn't the error pops up?
What is the reason to allow such programming?

Primarily because expressions in C also yield values. For example: x = 1; yields the value 1. Sometimes you use that for multiple assignment like x = y = 1;, but more often you don't.
In early C, the void return type hadn't been invented either, so every function returned some value, whether it was generally useful or not (for example, your call to printf also returns a value).
The rules of the language don't make this an error (doing so would lose compatibility with virtually existing code) and since this is common and rarely indicates a problem, most compilers don't warning about it either. A few lint tools do, which has led a few misguided programmers to write things like (void)printf("whatever"); (i.e., casting the unused return to void to signal that it really, truly was intentional when it was ignored. This, however, rarely does any good, and frequently does quite a bit of harm, so (thankfully) it's rarely seen.

Functions that return a value have that functionality for the use and convenience of the programmer. If you aren't interested in the return value, then don't use it.

Do you need the return value in this example? NO. So you have not used that in this case. But in another situation the return value might be important. For example if you want to read as long as some integer in available in input stream, then you can do something like this:
while (scanf("%d", &i) == 1) {
// do something
}
If there is an EOF then this loop will break. Here return value is needed.
So the summary is use return value when needed, and don't use when not needed. Such programming is allowed because both scenario is possible.

A lot of library functions return values you might not think about. Imagine having to use the return value of every printf call! (printf returns the number of characters printed.)

Pretty much every native c function returns a int. scanf and printf included. It would be really annoying if you always had to "capture" it to satisfy the compiler; In a large program you would end up creating thousands of variables just for storing return values that you never look at.

The reason is that C has no other established way of handling errors than by return value. These returned values, that is to say those return to report success or failure, should almost always be checked (unless you're just doodling around or you have a proof that the function will not fail).
Now since return values are also used for other things than returning success/failure information there might be, and are, situations where you will not be interested in the value a function returns, but just the side effects of executing it. In this case forcing the programmer to inspect/bind the returned value would become quite tideous.

Simple: if you don't use the return value, you don't use it.
It is not mandated that you do.
(That said, in a case like this, you should: you have no idea at present whether scanf encountered an error.)

It is not the case that everytime a value is evaluated,& it must be stored or returned,because the value you have obtained may be used by some other functions,to evaluate different kind of things.A value may be a measure...for example consider the following simple programm,where we want to check that the number entered is even or not
'int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a%2==0)
printf("even number");
else
printf("odd no");
return 0;
}'
here the variable 'a' is not necessarily to be returned,because we just want to check that the number is even or odd...no need of returning

Related

Should you check parameters passed into function before passing them, or check them in the function?

As a good practice, do you think one should verify passed parameters within a function to which the parameters are being passed, or simply make sure the function will always accept correct parameters?
Consider the following code:
Matrix * add_matrices(const Matrix * left, const Matrix * right)
{
assert(left->rowsCount == right->rowsCount
&& left->colsCount == right->colsCount);
int rowsCount = left->rowsCount;
int colsCount = left->colsCount;
Matrix * matOut = create_matrix(rowsCount, colsCount);
int i = 0;
int j = 0;
for (i; i < rowsCount; ++i)
{
for (j; j < colsCount; ++j)
{
matOut->matrix[i][j] = left->matrix[i][j] + right->matrix[i][j];
}
}
return matOut;
}
Do you think I should check the parameters before passing them to the function or after, ie. in the function? What is a better practice or is it programmer dependant?
Inside. The function can be viewed as an individual component.
Its author is best placed to define any preconditions and check them.
Checking them outside presupposes the caller knows the preconditions which may not be the case.
Also by placing them inside the function you're assured every call is checked.
You should also check any post-conditions before leaving the function.
For example if you have a function called int assertValid(const Matrix*matrix) that checks integrity of the object (e.g. the data is not a NULL pointer) you could call it on entry to all functions and before returning from functions that modify a Matrix.
Consistently use of pre- and post- condition integrity are an enormously effective way of ensuring quality and localising faults.
In practice zealous conformance to this rule usually results in unacceptable performance. The assert() macro or a similar conditional compilation construct is a great asset. See <assert.h>.
Depends if the function is global in scope or local static.
A global function cannot control what calls it. Defensive coding will perform validation of the arguments received. But how much validation to do?
int my_abs(int x) {
assert(x >= -INT_MAX);
return abs(x);
}
The above example, in a debug build, checks to insure the absolute value function will succeed as abs(INT_MIN) may be a problem. Now if this checking should be in production builds is another question.
int some_string(char *s) {
assert(s != NULL);
...
}
In some_string() the test for NULL-ness may be dropped as function definition may state that s must be a string. Even though NULL is not a C string, testing for NULL-ness is only 1 of many bad pointers that could be passed which do not point to a string. So this test has limited validation.
With static functions, the code is under local control. Argument validation could occur by the function, the caller, both or neither. That selection is code dependent.
A counter-example exist with user/file input. Basic data qualification should occur promptly.
int GetDriversAge(FILE *inf) {
int age;
if (fscanf("%d", &age) != 1) Handle_Error();
if (age < 16 || age > 122) Handle_Error();
return age
}
In OP's example, parameter checking is done by the function, not the caller. Without the equivalence test, the function can easily fail in mysterious ways. The cost of this check here is a small fraction of the code's work. That makes it a good check as expensive checks (time, complexity) can cause more trouble than they solve. Note that if the calling code did this test and add_matrices() was called from N places, then that checking code is replicated N times in various, perhaps, inconsistent ways.
Matrix * add_matrices(const Matrix * left, const Matrix * right) {
assert(left->rowsCount == right->rowsCount
&& left->colsCount == right->colsCount);
Conclusion: more compelling reasons to check the parameters in the function than in the caller though exceptions exist.
What I do is to check the parameters inside the function and act accordingly (throw exceptions, return error messages, etc.). I suppose it's the function's job to check whether the passed parameters are of the correct data type and contain valid values.
The function should perform its task correctly, otherwise, it should throw an exception. The client/consuming code may or may not do a check, it depends on the data source and how much you trust it, either way, you should also enclose the function call in a catch-try block to catch invalid argument exception.
EDIT:
Sorry, I confused C for C++. Instead of throwing an exception, you can return null. The client doesn't necessarily have to check the data before calling (depending on the data source and other factors like performance constraints), but must always check for null as a return value.

On understanding how printf("%d\n", ( { int n; scanf("%d", &n); n*n; } )); works in C

I came across this program via a quora answer
#include<stdio.h>
int main() {
printf("%d\n", ( { int n; scanf("%d", &n); n*n; } ));
return 0;
}
I was wondering how does this work and if this conforms the standard?
This code is using a "GNU C" feature called statement-expressions, whereby a parentheses-enclosed compound statement can be used as an expression, whose type and value match the result of the last statement in the compound statement. This is not syntactically valid C, but a GCC feature (also adopted by some other compilers) that was added presumably because it was deemed important for writing macros which do not evaluate their arguments more than once.
You should be aware of what it is and what it does in case you encounter it in code you have to read, but I would avoid using it yourself. It's confusing, unnecessary, and non-standard. The same thing can almost always be achieved portably with static inline functions.
I don't believe it does work... n has local scope within the braces... when you exit the braces, n becomes undefined though I suppose is could still exist somewhere on the stack and might work. It's begging for implementation issues and I guarantee is implementation dependent.
One thing I can tell you is that anyone working for me who wrote that would be read the riot act.
It works. I get no warnings from gcc, so I suppose that it conforms to the standard.
The magic is the closure:
{ int n; scanf("%d", &n); n*n; }
This nugget scans an integer from the console (with no error checking) and squares it, returning the squared number. In ancient implementations of C, the last number on the stack is returned. The n*n puts the number on the stack.
That value gets passed to the printf:
printf("%d\n", <scanned>);
So, to answer your questions: Yes, it works. Yes, it's "standard" (to the extent that anyone follows the standard entirely). No, it's not a great practice. This is a good example of what I by knee-jerk reaction call a "compiler love letter", designed mostly to show how smart the programmer is, not necessarily to solve a problem or be efficient.

Pass by reference in C: how is result variable initialized?

I am new to C, and I have to make a mini calculator program (this is homework, but I'm not looking for the answer, just a little more understanding). Basically, one function must look like this:
int add(double d, double dd, double *result);
It will return a 0 if there are no errors, and -1 if an error occurred (in the case of addition, there wouldn't be many errors - but division for example, divide by 0 would be an error).
A user has to input two numbers into the terminal, those numbers then get used as the parameter values in the add method. What I don't understand is what is result initially when the method is called? Is it just null? And why would I want to return 0 or -1 and not result instead? For example:
double result;
returnValue = add(2.0, 5.0, &result);
Obviously I'll get 7 as the result, but how will I print that out without returning the result? returnValue is 0, so I know there were no errors, so now I need to print result.
C doesn't have pass by reference. You can pass in a pointer, which is what you're doing here, but C only has pass by value.
Now to your actual questions:
What I don't understand is what is result initially when the method is called? Is it just null?
No, the value of result is undefined before the add function is called. You have no guarantees whatsoever if you try to use the value of result before assigning to it, either by assigning to it in the function where it's declared or by assigning to it in add with code like *result = d + dd.
For that matter, a double can never be null. Null is a possible pointer value, not a possible floating-point number.
And why would I want to return 0 or -1 and not result instead?
If you were to return result directly, you'd have to have some kind of distinguished "calculation failed" return value, which is kind of messy and leaves the caller to check the result before using it. This way forces the caller of add to notice that there is status code as the return value, and if the caller wants to ignore it then they can (although you shouldn't ignore status codes).
Obviously I'll get 7 as the result, but how will I print that out without returning the result?
Ed Heal is right to suggest printf. If you're using Linux or Mac OS X, though, I'd also recommend running man printf from the terminal - it's often more convenient than opening a web browser.
Thank you for your honesty. It is refreshing.
The line should read
returnValue = add(2.0, 5.0, &result);
And to print out the result look up printf - That will do the trick.
The code you have written does not assign a value to result when the variable is declared. Thus it contains some random number. It is obviously bad to use this number to do anything, as it will cause your program to have unpredictable results. This would be what is referred to as an uninitialized variable error.
Your code does not refer to the variable before it is assigned, so I am not saying you have a bug. I am simply answering the question of what result contains before it is assigned to. If you want it to have a particular value, you can declare it like this:
double result = 7;
and it would always have some predefined value. Again, there is no need to do this in your case, I'm just saying you could if you wanted an always defined value.

recursive functions in C: is return always necessary?

this is my first time playing with recursive functions, and this function that I wrote returns the size of a string if it contains only letters in ascending order, and if not it returns -1.
I don't understand why it works for both codes, after I took out the second "return". Is one more wasteful than the other? Would appreciate some insight.
with "return only_ascending_letters(string, index+1);"
#include <stdio.h>
int only_ascending_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="aabcdefg";
printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));
}
int only_ascending_letters(char string[], int index){
if(!string[index]) return index;
if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1]))
return only_ascending_letters(string, index+1);
else return -1;
}
with "only_ascending_letters(string, index+1);"
#include <stdio.h>
int only_ascending_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="aabcdefg";
printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));
}
int only_ascending_letters(char string[], int index){
if(!string[index]) return index;
if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1]))
/*Took out the return*/ only_ascending_letters(string, index+1);
else return -1;
}
Yes, you absolutely need the return. Note that C language rules are a bit lax about this issue, and if you hadn't used the return value, it would be fine without it. However, you use the return value, so you need the return statement.
What you see is probably caused by the implementation detail that function on some architectures return (integral values) by setting a well known register to that value (eax on i386). Therefore, if the bottommost recursive call does return and set this register, and the calls in-between don't stomp on that register, you see that it sort of works. However, you mustn't rely on that.
Note that good compilers will recognize this is a tail-recursive call and compile both variant basically the same way.
First of all, main() returns an int (actually, a type compatible with int).
Second, you should format your code more. Whitespace is your friend, as are line breaks. It was hard to tell whether the code without return was actually correct because most of it ran offscreen.
Third, you should always work with all [reasonable] warnings enabled. Doing so would have caught the missing return condition, as well as the void main().
As for the answer, #jpalecek has done a great job providing it. I would only like to add that undefined behavior is a beast. If you rely on it, a "working" program may stop doing so just because you decided to compile it again, played some music while running it, or the phase of the moon changed.
All I could find in the [99] standard was §6.9.1 clause 12:
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
You have two exit conditions. You either run off the end of the string, in which case your condtion of ascending characters is met and you return the length of the string, or you find a character that fails your ascending test, in which case you return -1.
Not returning the value from the call to the recursive function may work on some implementations of the compiler but with a different compiler or different optimisation flags, it may well not work so you should keep the return in your code.

How to return string from a char function

I want the function getCategory() to return "invalid" , instead of printing the word "invalid" (i.e instead of using printf ) when input to the function is invalid (i.e.when either height or weight are lower then zero).
please help:
#include<stdio.h>
#include<conio.h>
char getCategory(float height,float weight)
{
char invalid = '\0';
float bmirange;
if(height<=0 || weight<=0)
return invalid;
else
{
height=height*0.01; //1 centimeter = 0.01 meters
bmirange=[weight/(height*height)];
if(bmirange< 15 )
return starvation;
}
}
int main()
{
char Category;
float height,weight;
printf("enter height");
scanf("%f",&height);
printf("enter weight");
scanf("%f",&weight);
Category=getCategory(height,weight);
if(Category == 0)
printf("invalid");
else
printf("%c", Category);
}
NOTE: the original question has been altered many, many times and the code has changed just as often, introducing new errors in each iteration. I leave this answer as it answered the original code, see history. Below this answer there's an update giving advice instead of code, as that seems more appropriate here.
Hmm, astander removed his answer. But perhaps this is what you should actually have:*
char getCategory(float height,float weight)
{
char invalid = '\0';
if(height<=0 || weight<=0)
return invalid;
return 'c'; /* do something for the valid cases */
}
* originally the question contained height || weight <= 0 and no value for variable invalid.
Notes on the code:
With proper indentation, your program flow becomes clearer. I corrected your if-statement, assuming this was your intend, actually. The last line should contain what you currently left out in your question. I added an initialization in the first line, because having a value is better then not having a value (which means: if you don't initialize, it can be anything, really).
In your calling code, you can do this:
Category = getCategory(height, weight);
if(Category == 0)
printf("invalid");
else
printf("%c", Category);
which actually prints the word "invalid" to the output, if that was your intend.
Update: based on new text in the question, it's clear that the asker wants something else, so here's a new answer. I leave the above, it's still valid with the original question.
You're now asking not to print the word "invalid" and not to use a special value for the invalid case. Instead, you ask to return "invalid", which I understand as returning the string with the value "invalid" (which, taken in itself, is still returning a special value).
You cannot do it
In short: you cannot do that. The current function has return type char. I don't know the purpose of your function, but I'm sure you've given it some thought and there's a reason for using a char. A char can only contain one character. And the word "invalid" is multiple characters. You have a few options, choose whichever suits you best:
Other ways
change the return type to be string instead of char, this requires redesign of all code involved;
settle with returning a special value. You don't show the body of your function, but if it would normally never return \0, you can use that value, as in my example above. Of course, you can choose any other char value;
raise an exception and use a try/catch in the body. But you use C, not C++. Here's a link that describes using C++-style exception handling for C, but this may be a bit out-of-bounds, learning C can better be taken on a small step at the time.
What's commonly best practice
In normal situations, it is common to choose either special-case values (typical in older or more basic languages like C or assembler) or exceptions (typical for more structured languages like C++, Java, Python). It's commonly considered bad practice to change a complete function for the purpose of special-cases (like invalid input).
Why
Instead, the caller of the function should deal with these special cases. The reason for this is a very important rule in programming: the function can never know beforehand what users of that function want to do when something bad happens (illegal input). One may choose to print "Illegal input" (for commandline users), another wants to quit the program (for in a library) and yet another wants to ignore and do nothing (for automatic processing). In short: what you are trying to achieve, you should try to achieve differently (see option 2 and 3 above, and my original solution).
Teachers and textbooks
Using this approach is by far the easiest and also best to understand for any (future) co-workers as it follows common computer practices. Of course, I haven't seen your assignment or textbook, so I can't tell in what direction they want a solution, and it won't be the first textbook or teacher to first show you the wrong path, let you tremble, and then show you the right path.
The getCategory method doesn't always return (because of the if statement). Also, not sure about the height in if statement. Add another return invalid at the end of the method.
char getCategory(float height,float weight)
{
char invalid;
if(height<=0 || weight<=0)
return invalid;
return 0
}
you need to (very carefully) pore over your textbook to ascertain the multitude of errors in the above code.
1, your test in getCategory will almost certainly not do what you want it to do.
2, you ARE returning invalid in some cases (but not all, see #1). However, there is no way to know that as invalid has no known value.
3. in other cases, getCategory returns no value at all
You're defining a variable named invalid. Its contents are undefined (it could be anything from -128 to 127). When you return this variable you're returning anything; do you want to assign something to the invalid variable before you return it? e.g.
char invalid;
invalid = 'i';
if ( ... ) {
return invalid;
} else {
return 0;
}
What does invalid should be mapped to? You should have a convention like this:
char invalid_category = '?';
or perhaps:
#define INVALID_CATEGORY '?'
This is better defined outside of the getCategory function so that the calling code can access it.
Also it isn't evident what your code returns when valid arguments are passed to it.
By the way, in your function getCategory, you have a variable that is not used nor declared - starvation. Where does that come from? I doubt that is a global variable.
Also, the variable bmirange does not make sense nor would it compile
bmirange=[weight/(height*height)];
as you can see that is a left hand side expression (LHS) but you have used an array subscript operators on the right hand side of expression (RHS). That is an illegal statement!
What was your intention there? Was that meant to be a pair of parenthesis?
Can you confirm this?
A lot of the answers are confusing because the OP did not make themselves clear on what is the error nor an explanation as to what is going on which is leading others to end up with code posted that does not satisfy the OP.
Hope this helps,
Best regards,
Tom.

Resources