Explain function returns in c [closed] - function

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Why do these message functions return the return value of the printf ?
I know this code should not be used, it was just out of curiosity
#include<stdio.h>
message1()
{
printf("%d",(printf("Good")+printf("Morning")));
}
message2()
{
printf("%d",printf("Good"),printf("Morning"));
}
message3()
{
printf("%d",(printf("Good"),printf("Morning")));
}
int main()
{
printf("%d\n",message1());
printf("%d\n",message2());
printf("%d\n",message3());
return 0;
}

When you write:
message1()
{
...
}
The function is assumed to return an int. It is usually better to make it explicit:
int message1()
But your functions do not have any return, so the return value is undefined.
In your case, it happens that, by chance, the value stored as return value is the return value of the previous function call, that is printf(). But you should never trust in this.

printf returns the number of characters printed. The part you seem to be asking about then boils down to comparing these:
printf("%d", (4 + 7));
printf("%d", 4, 7);
printf("%d", (4, 7));
In the first one, 4 + 7 gives 11. In the second one, 4 is printed and the excess argument is ignored (because no format specifier corresponds). In the third one , (4, 7) is an expression featuring the comma operator and so it evaluates to 7.
NB. As everyone has pointed out, your code causes undefined behaviour by not returning a value from the function which returns int. You seem to be asking two different questions: why do your functions appear to return a value anyway; and what is the explanation of the other output you see.
The explanation of the first part is that it's undefined behaviour; to fix this you should change your functions to:
int message1(void)
{
return printf("%d", (printf("Good")+printf("Morning")));
}
and so on (which I assume is what your intention was when you wrote the function).

Your message functions lack a return type. C deduces it to be int. However, not returning a value from a non-void function is Undefined Behaviour.
In your case, the return value from printf has probably been stored in a register, which was not overwritten by message before it itself returned. Thus, the return value propagated.
While this can seem to ba all good and dandy, don't forget that UB is random by definition, and that you ought to avoid it at all cost (lest you want your program to mysteriously blow up when you change compiler / OS / Moon phase). Enabling (and acknowledging) compiler warnings would have saved you here.

the functions you declared are implicitly declared as returning int. The compiler should warn you about that, and also tell you that it is deprecated: don't do deprecated stuff. Since you miss a return statement in them the return value is undefined. I guess you get the return value of printf because that's what is in the stack at that moment, in practice, just luck. You probably wouldn't have the same result if you defined a variable inside those functions.

Related

Is there a way to make Typescript consider function types non-equivalent when they have different parameter counts?

Consider the following code:
function typeTest(callback:(item1:number, item2:string)=>number):number {
return callback(5, "foo");
}
//This works:
typeTest((num : number, str : string) => { return num;} )
//But surprisingly, so does this, even though the supplied callback doesn't have enough parameters
typeTest((num : number) => { return num;} )
I'm trying to tell the compiler that the function "typeTest" takes a callback with two parameters. However, if I give it a callback with fewer parameters, it still works.
I presume Typescript thinks that the function defined as "(num : number) => number" implements the function type of "(number, item2)", basically ignoring the second parameter. That makes some sense, but we re-defined a callback type to take more parameters, and expected the compiler to tell us where we'd forgotten to re-implement the old callbacks.
I might be running into a fundamental property of Typescript's type system, but is there a way to tell the compiler, "No really - the passed in function needs to take all of these parameters"?
Edit :
As for the motivation: In our case, the we used to have a "setSortFunction" method that expected a method that took a single item and returned an integer. If you compared that integer amongst all of the items, you could sort the array. Later we changed it to accept the more standard, "take two items, compare them, and return -1, 0, or 1". So, now we know for a fact that our sort functions passed in need to take two items and compare them. If they don't, they are probably broken. So, we wanted a way to enforce the requirement that the sortFunction passed in accepted two parameters.
However, if I give it a callback with fewer parameters, it still works.
Yes. This is by design. Think about it : it's safe for the caller to call a function that doesn't care about the last few arguments. This is the way JS works in conventional code bases.
This will clarify it a bit more : https://github.com/Microsoft/TypeScript/wiki/Type%20Compatibility#comparing-two-functions

Best practices: what should an "IsValid" boolean function return when passed a null argument? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Given a bool validation function that takes an argument and returns true or false based on argument's compliance to some internal rules:
if the argument is null, should the function:
return false
return true
do neither and simply raise a ArgumentNullException
I would tend to believe the best practice is to raise the exception.
I am however curious to hear others experience on the subject.
Given the sole choice of a bool, I am personally tempted to return false, but could see benefits in returning true also, based on the context of the function's usage.
A null string for instance could be interpreted as empty and may be considered valid.
Are there best practice guidelines for this specific situation?
I am looking for a guideline, like ones found in books like Code Complete.
Does it always need to be a case by case?
I don't think there's a general best practice, it will depend on the semantics.
Does it make sense to receive null? If so, return true or false based on what makes more sense, e.g. an hypothetical isAlphaNumericString(String) returning true when passed null is most likely nonsensical, but returning false may make sense.
But if it makes no sense to receive null, then a null marks a problem in the call, raise an exception to enforce the caller to make sense.
As I interpret your question, your input-variable space is determined by each value the variable can take augmented by a null state. In SQL for example, this corresponds to some type, say INTEGER and NULL. In C++, for example, it corresponds to something like boost::optional<int> in which null means "uninitialized".
Now, I think the cleanest solution is to augment the result-space as well with null. This is also the choice both examples above follow (or at least commonly follow). For example, if a scalar function such as LENGTH() or also a comparison operator in SQL takes a NULL argument, it usually also returns NULL.
More on the theoretical side, this implements somthing like an isomorphism from the null-subspace in definition space to the null-subspace in result space (and the same holds for the complement, i.e. the non-null space). The advantage of this is tha you do not have to reinterpret your original function at all.

Is there any advantage in specifying types of variables and return type of functions?

I always set the types of my variables and functions, a habit I brought from my Java learning, seems the right thing to do.
But I always see "weak typing" in other people's code, but I can't disagree with that as I don't know what are the real advantages of keep everything strong typed.
I think my question is clear, but I gonna give some examples:
var id = "Z226";
function changeId(newId){
id = newId;
return newId;
}
My code would be like this:
var id:String = "Z226";
function changeId(newId:String):String{
id = newId;
return newId;
}
Yes, the big advantanges are:
faster code execution, because the runtime know the type, it does not have to evaluate the call
better tool support: auto completion and code hints will work with typed arguments and return types
far better readability
You get performance benefits from strongly typing. See http://gskinner.com/talks/quick/#45
I also find strongly typed code to be much more readable, but I guess depending on the person they may not care.
As pointed out by florian, two advantages of strongly typing are that development tools can can use the information to provide better code-hinting and code-completion, and that type, as an explicit indicator of how the variable or method is intended to be used, can make the code much easier to understand.
The question of performance seems to be up for debate. However, this answer on stackoverflow suggests that typed is definitely faster than untyped in certain benchmark tests but, as the author states, not so much that you would notice it under normal conditions.
However, I would argue that the biggest advantage of strong typing is that you get a compiler error if you attempt to assign or return a value of the wrong type. This helps prevent the kind of pernicious bug which can only be tracked down by actually running the program.
Consider the following contrived example in which ActionScript automatically converts the result to a string before returning. Strongly typing the method's parameter and return will ensure that the program will not compile and a warning is issued. This could potentially save you hours of debugging.
function increment(value) {
return value + 1;
}
trace(increment("1"));
// 11
While the points in the other answers about code hinting and error checking are accurate, I want to address the claim about performance. It's really not all that true. In theory, strong type allows the compiler to generate code that's closer to native. With the current VM though, such optimization doesn't happen. Here and there the AS3 compiler will employ an integer instruction instead of a floating point one. Otherwise the type indicators don't have much effect at runtime.
For example, consider the following code:
function hello():String {
return "Hello";
}
var s:String = hello() + ' world';
trace(s);
Here're the AVM2 op codes resulting from it:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 4 0 ; call hello()
pushstring 12 ; push ' world' onto stack
add ; concatenate the two
initproperty 5 ; save it to var s
findpropstrict 7 ; look up trace
getlocal_0 ; push this onto stack
getproperty 5 ; look up var s
callpropvoid 7 1 ; call trace
returnvoid
Now, if I remove the type indicators, I get the following:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 3 0
pushstring 11
add
initproperty 4
findpropstrict 6
getlocal_0
getproperty 4
callpropvoid 6 1
returnvoid
It's exactly the same, except all the name indices are one less since 'String' no longer appears in the constant table.
I'm not trying to discourage people from employing strong typing. One just shouldn't expect miracle on the performance front.
EDIT: In case anyone is interested, I've put my AS3 bytecode disassembler online:
http://flaczki.net46.net/codedump/
I've improved it so that it now dereferences the operands.

scala foreach and map initializers

Just seen an interesting possibility to initialize code blocks in Scala for high order functions such as foreach or map:
(1 to 3) map {
val t = 5
i => i * 5
}
(1 to 3) foreach {
val line = Console.readLine
i => println(line)
}
Is this some documented feature or should I avoid such constructs? I could imagine, the "initialization" block comes into the constructor and the closure itself becomes an apply() method?
Thanks Pat for the original Question (http://extrabright.com/blog/2010/07/10/scala-question-regarding-readline)
While the features used are not uncommon, I'll admit is is a fairly odd combination of features. The basic trick is that any block in Scala is an expression, with type the same as the last expression in the block. If that last expression is a function, this means that the block has functional type, and thus can be used as an argument to "map" or "foreach" . What happens in these cases is that when "map" or "foreach" is called, the block is evaluated. The block evaluates to a function ( i=> i*5 in the first case ), and that function is then mapped over the range.
One possible use of this construct is for the block to define mutable variables, and the resulting function mutate the variables each time it is called. The variables will be initialized once, closed over by the function, and their values updated every time the function is called.
For example, here's a somewhat surprising way of calculating the first 6 factorial numbers
(1 to 6) map {
var total = 1
i => {total *= i;total}
}
(BTW, sorry for using factorial as an example. It was either that or fibonacci. Functional
Progamming Guild rules. You gotta problem with that, take it up with the boys down at the hall.)
A less imperative reason to have a block return a function is to define helper functions earlier in the block. For instance, if your second example were instead
(1 to 3) foreach {
def line = Console.readLine
i => println(line)
}
The result would be that three lines were read and echoed once each, while your example had the line read once and echoed three times.
First, the comment of the original blog "Scala Question Regarding readLine" post mention
The “line” is a value and cannot be executed, it is assigned only once from the result of the “Console.readLine” method execution.
It is used less than three times in your closure.
But if you define it as a method, it will be executed three times:
(1 to 3) foreach {
def line = Console.readLine
i => println(line)
}
The blog Scala for Java Refugees Part 6: Getting Over Java has an interesting section on Higher Order function, including:
Scala provides still more flexibility in the syntax for these higher-order function things.
In the iterate invocation, we’re creating an entire anonymous method just to make another call to the println(String) method.
Considering println(String) is itself a method which takes a String and returns Unit, one would think we could compress this down a bit. As it turns out, we can:
iterate(a, println)
By omitting the parentheses and just specifying the method name, we’re telling the Scala compiler that we want to use println as a functional value, passing it to the iterate method.
Thus instead of creating a new method just to handle a single set of calls, we pass in an old method which already does what we want.
This is a pattern commonly seen in C and C++. In fact, the syntax for passing a function as a functional value is precisely the same. Seems that some things never change…

Best Practice: function return value or byref output parameters?

I have a function called FindSpecificRowValue that takes in a datatable and returns the row number that contains a particular value. If that value isn't found, I want to indicate so to the calling function.
Is the best approach to:
Write a function that returns false if not found, true if found, and the found row number as a byref/output parameter, or
Write a function that returns an int and pass back -999 if the row value isn't found, the row number if it is?
Personally I would not do either with that method name.
I would instead make two methods:
TryFindSpecificRow
FindSpecificRow
This would follow the pattern of Int32.Parse/TryParse, and in C# they could look like this:
public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber)
{
if (row-can-be-found)
{
rowNumber = index-of-row-that-was-found;
return true;
}
else
{
rowNumber = 0; // this value will not be used anyway
return false;
}
}
public static Int32 FindSpecificRow(DataTable table)
{
Int32 rowNumber;
if (TryFindSpecificRow(table, out rowNumber))
return rowNumber;
else
throw new RowNotFoundException(String.Format("Row {0} was not found", rowNumber));
}
Edit: Changed to be more appropriate to the question.
functions that fail should throw exceptions.
If failure is part of the expected flow then returning an out of band value is OK, except where you cannot pre-determine what an out-of-band value would be, in which case you have to throw an exception.
If I had to choose between your options I would choose option 2, but use a constant rather than -999...
You could also define return value as Nullable and return Nothing if nothing found.
I would choose option 2. Although I think I would just use -1 not -999.
Richard Harrison is right that a named constant is better than a bare -1 or -999.
I would go with 2, or some other variation where the return value indicates whether the value was found.
It seems that the value of the row the function returns (or provides a reference to) already indicates whether the value was found. If a value was not found, then it seems to make no sense to provide a row number that doesn't contain the value, so the return value should be -1, or Null, or whatever other value is suitable for the particular language. Otherwise, the fact that a row number was returned indicates the value was found.
Thus, there doesn't seem to be a need for a separate return value to indicate whether the value was found. However, type 1 might be appropriate if it fits with the idioms of the particular language, and the way function calls are performed in it.
Go with 2) but return -1 (or a null reference if returning a reference to the row), that idiom is uses extensively (including by by .nets indexOf (item) functions), it's what I'd probably do.
BTW -1 is more acceptable and widly used "magic number" than -999, thats the only reason why it's "correct" (quotes used there for a reason).
However much of this has to do with what you expect. Should the item always be in there, but you just don't know where? In that case return the index normally, and throw an error/exception if it's not there.
In this case, the item might not be there, and that's an okay condition. It's an error trap for unselected values in a GridView that binds to a datatable.
Another few possibilities not yet mentioned:
// Method 1: Supports covariance; can return default<T> on failure.
T TryGetThing(ref bool success);
// Method 2: Does not support covariance, but may allow cleaner code in some cases
// where calling code would use some particular value in in case of failure.
T TryGetThing(T DefaultValue);
// Method 3: Does not support covariance, but may allow cleaner code in some cases
// where calling code would use some particular value in case of failure, but should
// not take the time to compute that value except when necessary.
T TryGetThing(Func<T> AlternateGetMethod);
// Method 4: Does support covariance; ErrorMethod can throw if that's what should
// happen, or it can set some flag which is visible to the caller in some other way.
T TryGetThing(Action ErrorMethod);
The first approach is the reverse of the method Microsoft developed in the days before support existed for covariant interfaces. The last is in some ways the most versatile, but is likely to require the creation of a couple of new GC object instances (e.g. a closure and a delegate) each time it's used.