function return not assigned to a variable - function

What if you call a (non-void) function, but don't assign its return value to a variable?
e.g., getchar();
I've always wondered what happens to such a value. I've heard humorous explanations like "its gone to the ether" and so forth, but I'd really like to know really. Would there be any way to recover such a value?
Thanks

This is really compiler / CPU specific, but in most cases the return value will be in a CPU register (if it will fit), and if that register is not touched by the subsequent code, you could retrieve it using e.g. "inline assembler".
To answer your question better, nothing "happens" to the value. It sits in a stack-location or inside a register. If you use it, fine... if not, nothing happens really. Eventually the stack or register is overwritten by new values...

No, you won't.
The value gets popped off the stack and is gone.
If you need the return value, you should assign it to a variable.

Simply 'returning' (either by implicitly calling return by itself or not returning at all) and not assigning a value does just that, doesn't assign a value and thus is null.

If you want to learn more about how it all works, you can look at this: http://en.wikipedia.org/wiki/Call_stack

Related

What does a period with a name before a function mean when calling it in Arduino code (C/C++)?

What does a period with a name before a function mean when calling it in Arduino code (C/C++)?
For example, I am using an OLED display library and one function is called like this:
display.setTextSize(1);
I know what this function does, but what does the syntax mean where there is some variable "display" or something before it?
In other words, why is a function called this way versus a normal call with just the function name and input?
"display" is an instance of an object, or a reference to some global/system variable. The "setTextSize" method is a member of that object. The end result means that you are setting the text size of, or on, "display".
This lets you do things more concisely by being able to say display.setTextSize(1), foo.setTextSize(1) and bar.setTextSize(1) without having to specify unique functions for each different item on which you are setting the text size.
Within setTextSize you will probably see "this". "this" in only this one instance means "display". If you used bar.setTextSize(1), "this" would mean "bar" and so on.
I could be incredibly wrong, but I think its got to do with structures. In the arduino environment there's a few different functions that revolve around using serial communication. They have it set up as a library that gets called on whenever you use Serial.something();
The something could be any of the functions that is part of serial, like Serial.read();
EDIT forgot to put a source in. http://arduino.cc/en/Reference/Serial
Apologies if I'm way off, still new at this, and also can't figure out how to just make a comment.

Style Question: if block in or around function?

Let's say that I have a function that should only execute if some constant is defined. which of the following would be better
Option 1: wrap all the function calls in an if block:
if(defined('FOO_BAR_ENABLED')) {
foobar();
}
I figure this way the intent is more clear, but it requires checking the constant every time the function is called.
Option 2: check the constant in the function itself:
function foobar() {
if(!defined('FOO_BAR_ENABLED')) {
return;
}
//do stuff
}
This way requires less lines of code, and the constant is sure to get checked. However, I find it confusing to see calls to this function when it's not actually doing anything. Thoughts?
May I suggest renaming the function to FoobarIfEnabled(), then doing the check in the function?
Stealing liberally from a great language-agnostic answer to one of my own questions, when programming we have the following concerns:
Make it correct.
Make it clear.
Make it concise.
Make it fast. ... in that order.
If you do the check outside the function, you might end up missing it in one place. And if you want to change the behavior, you'll have to find all the places it gets called and fix it. That's a maintenance nightmare which violates principle 1. By adding "IfEnabled" or something like that to the name, now it is not just correct but also is clear. How can you beat that?
Performance is not to be worried about unless the final speed is unsatisfactory and you have identified this as the bottleneck (unlikely).
I recommend you follow the link above and read as it was a very useful answer that gave me much to think about.
Option 3:
void maybe_foobar() {
if(defined('FOO_BAR_ENABLED')) really_foobar();
}
void really_foobar() {
// do stuff
}
On a good day I'd think of better names than "maybe" and "really", but it depends what the function does and why it's turn-off-and-onable.
If there is no circumstance under which anyone could validly "do stuff" when FOO_BAR_ENABLED isn't defined, then I'd go with your option 2 (and perhaps call the function do_stuff_if_possible rather than foobar, if the name foobar was causing confusion as to whether calling it entails actually doing anything). If it's always valid to "do stuff", but some users just so happen do so conditionally, then I'd go with my option 3.
Option 1 is going to result in you copy-and-pasting code around, which is almost always a Bad Sign.
[Edit: here's Option 4, which I suspect is over-engineering, but you never know:
void if_enabled(string str, function f) {
if (defined(str + '_ENABLED')) f();
}
Then you call it with:
if_enabled('FOO_BAR', foobar);
Obviously there's some issues there to do with how your language handles functions, and whether there's any way to pass arbitrary parameters and a return value through if_enabled.]
Does the condition of the if fall within the function's responsibility? Is there a use case for calling the function without the if?
If the condition always needs to be checked, I'd put it in the function. Follow the DRY principle here: Don't Repeat Yourself. Another quip that might be helpful is the SRP - the Single Responsibility Principle - do one thing, and do it well.
In the header file, if foobar always takes the same number of arguments,
#ifdef ENABLE_FOOBAR
#define maybe_foobar(x) foobar(x)
#else
#define maybe_foobar(x)
#endif
Not sure how to do that in C++ or older C dialects if foobar can take a variable number of arguments.
(Just noticed language-agnostic tag. Well, the above technique is what I'd suggest in languages where it works; maybe use an inline function for languages which have those but lack macros).
Option 2, less code and it ensures the constant is defined, as you suggested.
Since this is apparently only used with the foobar() function, then option 2 should be your choice. That means the test is located in only one place and your code is more readable.

How should substring() work?

I do not understand why Java's [String.substring() method](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#substring(int,%20int%29) is specified the way it is. I can't tell it to start at a numbered-position and return a specified number of characters; I have to compute the end position myself. And if I specify an end position beyond the end of the String, instead of just returning the rest of the String for me, Java throws an Exception.
I'm used to languages where substring() (or substr()) takes two parameters: a start position, and a length. Is this objectively better than the way Java does it, and if so, can you prove it? What's the best language specification for substring() that you have seen, and when if ever would it be a good idea for a language to do things differently? Is that IndexOutOfBoundsException that Java throws a good design idea, or not? Does all this just come down to personal preference?
There are times when the second parameter being a length is more convenient, and there are times when the second parameter being the "offset to stop before" is more convenient. Likewise there are times when "if I give you something that's too big, just go to the end of the string" is convenient, and there are times when it indicates a bug and should really throw an exception.
The second parameter being a length is useful if you've got a fixed length of field. For instance:
// C#
String guid = fullString.Substring(offset, 36);
The second parameter being an offset is useful if you're going up to another delimited:
// Java
int nextColon = fullString.indexOf(':', start);
if (start == -1)
{
// Handle error
}
else
{
String value = fullString.substring(start, nextColon);
}
Typically, the one you want to use is the opposite to the one that's provided on your current platform, in my experience :)
I'm used to languages where
substring() (or substr()) takes two
parameters: a start position, and a
length. Is this objectively better
than the way Java does it, and if so,
can you prove it?
No, it's not objectively better. It all depends on the context in which you want to use it. If you want to extract a substring of a specific length, it's bad, but if you want to extract a substring that ends at, say, the first occurrence of "." in the string, it's better than if you first had to compute a length. The question is: which requirement is more common? I'd say the latter. Of course, the best solution would be to have both versions in the API, but if you need the length-based one all the time, using a static utility method isn't that horrible.
As for the exception, yeah, that's definitely good design. You asked for something specific, and when you can't get that specific thing, the API should not try to guess what you might have wanted instead - that way, bugs become apparent more quickly.
Also, Java DOES have an alternative substring() method that returns the substring from a start index until the end of the string.
second parameter should be optional, first parameter should accept negative values..
If you leave off the 2nd parameter it will go to the end of the string for you without you having to compute it.
Having gotten some feedback, I see when the second-parameter-as-index scenario is useful, but so far all of those scenarios seem to be working around other language/API limitations. For example, the API doesn't provide a convenient routine to give me the Strings before and after the first colon in the input String, so instead I get that String's index and call substring(). (And this explains why the second position parameter in substr() overshoots the desired index by 1, IMO.)
It seems to me that with a more comprehensive set of string-processing functions in the language's toolkit, the second-parameter-as-index scenario loses out to second-parameter-as-length. But somebody please post me a counterexample. :)
If you store this away, the problem should stop plaguing your dreams and you'll finally achieve a good night's rest:
public String skipsSubstring(String s, int index, int length) {
return s.subString(index, index+length);
}

Should I always/ever/never initialize object fields to default values?

Code styling question here.
I looked at this question which asks if the .NET CLR will really always initialize field values. (The answer is yes.) But it strikes me that I'm not sure that it's always a good idea to have it do this. My thinking is that if I see a declaration like this:
int myBlorgleCount = 0;
I have a pretty good idea that the programmer expects the count to start at zero, and is okay with that, at least for the immediate future. On the other hand, if I just see:
int myBlorgleCount;
I have no real immediate idea if 0 is a legal or reasonable value. And if the programmer just starts reading and modifying it, I don't know whether the programmer meant to start using it before they set a value to it, or if they were expecting it to be zero, etc.
On the other hand, some fairly smart people, and the Visual Studio code cleanup utility, tell me to remove these redundant declarations. What is the general consensus on this? (Is there a consensus?)
I marked this as language agnostic, but if there is an odd case out there where it's specifically a good idea to go against the grain for a particular language, that's probably worth pointing out.
EDIT: While I did put that this question was language agnostic, it obviously doesn't apply to languages like C, where no value initialization is done.
EDIT: I appreciate John's answer, but it is exactly what I'm not looking for. I understand that .NET (or Java or whatever) will do the job and initialize the values consistently and correctly. What I'm saying is that if I see code that is modifying a value that hasn't been previously explicitly set in code, I, as a code maintainer, don't know if the original coder meant it to be the default value, or just forgot to set the value, or was expecting it to be set somewhere else, etc.
Think long term maintenance.
Keep the code as explicit as possible.
Don't rely on language specific ways to initialize if you don't have to. Maybe a newer version of the language will work differently?
Future programmers will thank you.
Management will thank you.
Why obfuscate things even the slightest?
Update: Future maintainers may come from a different background. It really isn't about what is "right" it is more what will be easiest in the long run.
You are always safe in assuming the platform works the way the platform works. The .NET platform initializes all fields to default values. If you see a field that is not initialized by the code, it means the field is initialized by the CLR, not that it is uninitialized.
This concern is valid for platforms which do not guarantee initialization, but not here. In .NET, is more often indicates ignorance from the developer, thinking initialization is necessary.
Another unnecessary hangover from the past is the following:
string foo = null;
foo = MethodCall();
I've seen that from people who should know better.
I think that it makes sense to initialize the values if it clarifies the developer's intent.
In C#, there's no overhead as the values are all initialized anyway. In C/C++, uninitialized values will contain garbage/unknown values (whatever was in the memory location), so initialization was more important.
I think it should be done if it really helps to make the code more understandable.
But I think this is a general problem with all language features. My opinion on that is: If it is an official feature of the language, you can use it. (Of course there are some anti-features which should be used with caution or avoided at all, like a missing option explicit in Visual Basic or diamond inheritance in C++)
There was I time when I was very paranoid and added all kinds of unnecessary initializations, explicit casts, über-paranoid try-finally blocks, ... I once even thought about ignoring auto-boxing and replacing all occurrences with explicit type conversions, just "to be on the safe side".
The problem is: There is no end. You can avoid almost all language features, because you do not want to trust them.
Remember: It's only magic until you understand it :)
I agree with you; it may be verbose, but I like to see:
int myBlorgleCount = 0;
Now, I always initial strings though:
string myString = string.Empty;
(I just hate null strings.)
In the case where I cannot immediately set it to something useful
int myValue = SomeMethod();
I will set it to 0. That is more to avoid having to think about what the value would be otherwise. For me, the fact that integers are always set to 0 is not on the tip of my fingers, so when I see
int myValue;
it will take me a second to pull up that fact and remember what it will be set to, disrupting my thought process.
For someone who has that knowledge readily available, they will encounter
int myValue = 0;
and wonder why the hell is that person setting it to zero, when the compiler would just do it for them. This thought would interrupt their thought process.
So do which ever makes the most sense for both you and the team you are working in. If the common practice is to set it, then set it, otherwise don't.
In my experience I've found that explicitly initializing local variables (in .NET) adds more clutter than clarity.
Class-wide variables, on the other hand should always be initialized. In the past we defined system-wide custom "null" values for common variable types. This way we could always know what was uninitialized by error and what was initialized on purpose.
I always initialize fields explicitly in the constructor. For me, it's THE place to do it.
I think a lot of that comes down to past experiences.
In older and unamanged languages, the expectation is that the value is unknown. This expectation is retained by programmers coming from these languages.
Almost all modern or managed languages have defined values for recently created variables, whether that's from class constructors or language features.
For now, I think it's perfectly fine to initialize a value; what was once implicit becomes explicit. In the long run, say, in the next 10 to 20 years, people may start learning that a default value is possible, expected, and known - especially if they stay consistent across languages (eg, empty string for strings, 0 for numerics).
You Should do it, there is no need to, but it is better if you do so, because you never know if the language you are using initialize the values. By doing it yourself, you ensure your values are both initialized and with standard predefined values set.
There is nothing wrong on doing it except perhaps a bit of 'time wasted'. I would recommend it strongly. While the commend by John is quite informative, on general use it is better to go the safe path.
I usually do it for strings and in some cases collections where I don't want nulls floating around.
The general consensus where I work is "Not to do it explicitly for value types."
I wouldn't do it. C# initializes an int to zero anyways, so the two lines are functionally equivalent. One is just longer and redundant, although more descriptive to a programmer who doesn't know C#.
This is tagged as language-agnostic but most of the answers are regarding C#.
In C and C++, the best practice is to always initialize your values. There are some cases where this will be done for you such as static globals, but there shouldn't be a performance hit of any kind for redundantly initializing these values with most compilers.
I wouldn't initialise them. If you keep the declaration as close as possible to the first use, then there shouldn't be any confusion.
Another thing to remember is, if you are gonna use automatic properties, you have to rely on implicit values, like:
public int Count { get; set; }
http://www.geekherocomic.com/2009/07/27/common-pitfalls-initialize-your-variables/
If a field will often have new values stored into it without regard for what was there previously, and if it should behave as though a zero was stored there initially but there's nothing "special" about zero, then the value should be stored explicitly.
If the field represents a count or total which will never have a non-zero value written to it directly, but will instead always have other amounts added or subtracted, then zero should be considered an "empty" value, and thus need not be explicitly stated.
To use a crude analogy, consider the following two conditions:
`if (xposition != 0) ...
`if ((flags & WoozleModes.deluxe) != 0) ...
In the former scenario, comparison to the literal zero makes sense because it is checking for a position which is semantically no different from any other. In the second scenario, however, I would suggest that the comparison to the literal zero adds nothing to readability because code isn't really interested in whether the value of the expression (flags & WoozleModes.deluxe) happens to be a number other than zero, but rather whether it's "non-empty".
I don't know of any programming languages that provide separate ways of distinguishing numeric values for "zero" and "empty", other than by not requiring the use of literal zeros when indicating emptiness.

What is the term for "catching" a return value

I was training a new developer the other day and realized I don't know the actual term for "catching" a return value in a variable. For example, consider this pseudocoded method:
String updateString(newPart) {
string += newPart;
return string;
}
Assume this is being called to simply update the string - the return value is not needed:
updateString("add this");
Now, assume we want to do something with the returned value. We want to change the call so that we can use the newly updated string. I found myself saying "catch the return value", meaning I wanted to see:
String returnedString = updateString("add this");
So, if you were trying to ask someone to make this change, what terminology would you use? Is it different in different languages (since technically, you may be calling either a function or a method, depending on the language)?
assign the return value to a variable?
Returned values can be assigned or discarded/ignored/not used/[insert synonym here].
There isn't really a technical term for it.
I would say "returnedString is to be initialised with the return value of updateString".
"Catch" makes me think of exceptions, which is a bit misleading. How about something like "use" or "store" or "assign"?
Common ones that I know:
You assign a value to a variable.
You store a value into a variable.
check the function's return value, do not ignore return values
In the example, you're simply assigning the return value of the function to a new variable.
When describing the behavior of that single line of code, it doesn't really matter that the return value is not essential to the use of the function. However, in a broader context, it is very important to know what purpose this "Interesting Return Value" serves.
As others have said there isn't really a word for what you describe. However, here's a bit of terminology for you to chew on: the example you give looks like it could be a Fluent Interface.
I suggest "cache", meaning store it for later.
Maybe there's a subliminal reason you're saying "catch".
It's better too state the purpose rather than the implementation details (because actual implementation can be different in different programming langugages).
Generally speaking:
- Save the return value of the call.
If you know the return value is a result of something:
- Save the result of the call.
If you know the return value is to signify a status (such as error):
- Save the status of the call.
By using the word "save", you can use that same statement across the board, regardless of the mechanism used in that particular language to save the return value.