reference interview questions
Top reference frequently asked interview questions
Why does the first return a reference?
int x = 1;
int y = 2;
(x > y ? x : y) = 100;
While the second does not?
int x = 1;
long y = 2;
(x > y ? x : y) = 100;
Actually, the second did not compile at all - "not lvalue left of assignment".
Source: (StackOverflow)
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
Is there something I can do to pass the variable by actual reference?
Source: (StackOverflow)
I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:
public void myFunction(ref MyClass someClass)
and
public void myFunction(out MyClass someClass)
Which should I use and why?
Source: (StackOverflow)
I know references are syntactic sugar, so code is easier to read and write.
But what are the differences?
Summary from answers and links below:
- A pointer can be re-assigned any number of times while a reference can not be re-seated after binding.
- Pointers can point nowhere (
NULL
), whereas reference always refer to an object.
- You can't take the address of a reference like you can with pointers.
- There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in
&obj + 5
).
To clarify a misconception:
The C++ standard is very careful to avoid dictating how a compiler must
implement references, but every C++ compiler implements
references as pointers. That is, a declaration such as:
int &ri = i;
if it's not optimized away entirely, allocates the same amount of storage
as a pointer, and places the address
of i into that storage.
So, a pointer and a reference both occupy the same amount of memory.
As a general rule,
- Use references in function parameters and return types to define useful and self-documenting interfaces.
- Use pointers to implement algorithms and data structures.
Interesting read:
Source: (StackOverflow)
I am trying to run some unit tests in a C# Windows Forms
application (Visual Studio 2005) and I get the following error:
System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**
at x.Foo.FooGO()
at x.Foo.Foo2(String groupName_) in Foo.cs:line 123
at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**
System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
I look in my references and I only have a reference to Utility version 1.2.0.203
(the other one is old).
Any suggestions on how I figure out what is trying to reference this old version of this DLL?
Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?
Source: (StackOverflow)
I'm new to MongoDB--coming from a relational database background. I want to design a question structure with some comments, but I don't know which relationship to use for comments: embed
or reference
?
A question with some comments, like stackoverflow, would have a structure like this:
Question
title = 'aaa'
content = bbb'
comments = ???
At first, I want to use embeded comments (I think embed
is recommended in MongoDB), like this:
Question
title = 'aaa'
content = 'bbb'
comments = [ { content = 'xxx', createdAt = 'yyy'},
{ content = 'xxx', createdAt = 'yyy'},
{ content = 'xxx', createdAt = 'yyy'} ]
It clear, but I'm worried about this case: If I want to edit a specified comment, how do I get its content and its question? There is no _id
to let me find one, nor question_ref
to let me find its question. (I'm so newbie, that I don't know if there's any way to do this without _id
and question_ref
.)
Do I have to use ref
not embed
? Then I have to create a new collection for comments?
Source: (StackOverflow)
What would be better practice when giving a function the original variable to work with:
unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
or:
void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
IOW: Is there any reason to pick one over another?
Source: (StackOverflow)
This question already has an answer here:
I have a C#
solution with several projects in Visual Studio 2010
.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application
project (I'll call it "PrjForm"). There is also a third project referenced by PrjForm, which it is able to reference and use successfully.
PrjForm references PrjTest, and PrjForm has a class with a using
statement:
using PrjTest;
- Reference has been correctly added
using
statement is correctly in place
- Spelling is correct
- PrjTest builds successfully
- PrjForm almost builds, but breaks on the
using PrjTest;
line with the error:
The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)
I've tried the following to resolve this:
- Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)
- Removed and re-added the reference and using statement
- Recreated PrjForm from scratch
- PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder
- Loaded the solution on a different computer with a fresh copy of
VS 2010
I have done my homework and spent far too long looking for an answer online, no solution has helped yet.
What else could I try?
Source: (StackOverflow)
My Google-fu has failed me.
In Python, are the following two tests for equality equivalent (ha!)?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
Does this hold true for objects where you would be comparing instances (a list
say)?
Okay, so this kind of answers my question:
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
So ==
tests value where is
tests to see if they are the same object?
Source: (StackOverflow)
I understand the syntax and general semantics of pointers versus references, what I can't decide is when is it more-or-less appropriate to use references or pointers in an API?
Naturally some situations need one or the other (operator++
needs a reference argument), but in general I'm finding I prefer to use pointers (and const pointers) as the syntax is clear that the variables are being passed destructively.
E.g. in the following code:
void add_one(int& n) { n += 1; }
void add_one(int* const n) { *n += 1; }
int main() {
int a = 0;
add_one(a); // not clear that a may be modified
add_one(&a); // a is clearly being passed destructively
}
With the pointer, it's always (more) obvious what's going on, so for APIs and the like where clarity is a big concern are pointers not more appropriate than references? Does that mean references should only be used when necessary (e.g. operator++
)? Are there any performance concerns with one or the other?
EDIT (OUTDATED):
Besides allowing NULL values and dealing with raw arrays, it seems the choice comes down to personal preference. I've accepted the answer below that references Google's C++ Style Guide, as they present the view that "References can be confusing, as they have value syntax but pointer semantics.".
EDIT:
Due to the additional work required to sanitise pointer arguments that should not be NULL (e.g. add_one(0)
will call the pointer version and break during runtime), it makes sense from a maintainability perspective to use references where an object MUST be present, though it is a shame to lose the syntactic clarity.
Source: (StackOverflow)
I have been unable to find a solution for this.
What I'm trying to do: I have preferences where you can enable/disable what items will show up on the menu. There are 17 items. I made a string array in values/arrays.xml with titles for each of these 17 items.
I have preferences.xml which has the layout for my preferences file, and I would like to reference a single item from the string array to use as the title.
How, if it's possible, can I do this?
In the Android developer reference, I see how I can reference a single string with XML, but now how I can reference a string from an array resource in XML.
Thanks
Source: (StackOverflow)
Does JavaScript pass by references or pass by values? Here is an example from JavaScipt: The Good Parts. I am very confused about my
parameter for the rectangle function. It is actually undefined
, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
Source: (StackOverflow)
I'm having another of these "Could not load file or assembly or one of its dependencies" problems.
Additional information: Could not load
file or assembly
'Microsoft.Practices.Unity,
Version=1.2.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' or
one of its dependencies. The located
assembly's manifest definition does
not match the assembly reference.
(Exception from HRESULT: 0x80131040)
I have no idea what is causing this or how I could debug it to find the cause.
I've done a search in my solution catalogs .csproj files, and every where I have Unity I have:
Reference
Include="Microsoft.Practices.Unity,
Version=2.0.414.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35,
processorArchitecture=MSIL"
Can't find any reference anywhere which goes against 1.2.0.0 in any of my projects.
Any ideas how I should go about solving this?
I would also appreciate tips on how to debug problems like this in general.
Source: (StackOverflow)
I have read that .NET supports return of references, but C# doesn't. Is there a special reason? Why I can't do something like:
static ref int Max(ref int x, ref int y)
{
if (x > y)
return ref x;
else
return ref y;
}
Source: (StackOverflow)