I have been looking through some code on an open source project recently and found many occurrences of this kind of code:
class SomeClass
{
private int SomeNumber = 42;
public ReturnValue UseSomeNumber(...)
{
int someNumberCopy = this.SomeNumber;
if (someNumberCopy > ...)
{
// ... do some work with someNumberCopy
}
else
{
// ... do something else with someNumberCopy
}
}
}
Is there any real benefit to making a copy of the instance variable?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.
Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.
The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.
Possibly this is part of multi-threaded program. Though this code is not thread-safe, it ensures that once copy variable is assigned, it is not changed by another threads, and all function code after this runs consistently.
Similar code with events becomes critical in multi-threaded environment:
MyEvent e = this.myEvent; if ( e != null ) { e(); }
Here, without making a local copy, it is possible to get null-pointer exception, if event becomes null after testing for null, and before invoking.
No unless you don't want to change the value of SomeNumber and you intend on updating someNumberCopy. Like if you were going to loop the number of times and were going to decrement someNumberCopy down to zero to keep track of the count.
I suppose copying the variable like that could protect you from some outside function altering SomeNumber and changing it without your knowledge while performing an operation. I could potentially see this if the class was supposed to be used in a multi-threaded application. Maybe not he way I would go about it, but that could have been the author's intent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With