C++ Warning if re-declaring member variable in function - c++

Given a structure such as below
class A {
int test;
void f() { int test; }
}
I just had a curious case in which the code in f(), when referring to test, compiled under VS2010, correctly referred to the function local variable, however, when compiled under gcc, incorrectly referred to the member variable. Took me quite a while to track down.
Anyway, question is, is there an option in gcc or VS to enable compiler warnings every time a member variable is re-declared in a local function scope?

In GCC, -Wshadow. From the documentation:
Warn whenever a local variable or type declaration shadows another
variable, parameter, type, or class member (in C++), or whenever a
built-in function is shadowed. Note that in C++, the compiler will not
warn if a local variable shadows a struct/class/enum, but will warn if
it shadows an explicit typedef.

I don't know if any such option exists.
But if it doesn't exist, then you can do the following. In fact, the naming convention is preferred even if there exists some compiler option to avoid the problem in the question, for it covers broader area of concerns:
class A {
int m_test; //use some naming conventions!
void f() { int test; }
};
That is, use some rules in naming the member variables, such as, prefix each with m_ as in m_test, Or use suffix as in test_. This is the usual approach adopted by many programmers, and in many companies, there is similar rules which they impose when coding.
Such naming conventions not only help avoiding the problem you came across, it also increases readability and maintainability, as the name test suggests nothing as to whether it is local variable or member variable in the absence of naming conventions. But once you adopt some naming conventions, such things become clear.

Related

When should I reuse variable names in C++

I know that you can reuse variable names in C++, but I'm wondering whether I should. I'm not talking about reusing the variable itself, like with global variables. I'm talking about declaring and using a variable with a certain name in one scope, and then declaring and using another variable with the same name in a different scope. For example:
void Func1(int b) { /* Code here. */ };
void Func2(int b) { /* Different code here. */ };
void main()
{
{
int a=1;
// Do stuff with this variable.
}
{
int a=5;
// Do different stuff with this variable.
}
int b=10:
Func1(b);
Func2(b);
}
It seems like doing this would allow for shorter variable names and allow copy and pasting of code without having to change the variable names, but it might cause confusion. Is there a style guide or generally accepted practice about when to do this?
I searched for a similar question to this and I couldn't find anything. I found some stuff about global variables, but that's not what I'm looking for.
The alleged benefit of shorter variable names may be of interest, but what is of greater interest is shorter variable scopes. Generally, the smaller the scope of the variable is, the better. Therefore, declaring variables within small scopes is a good practice, and introducing naked scopes purely for that purpose is good practice too.
Once we have gotten that out of the way, then we go to the question of whether it should be okay to reuse a variable name in different scopes.
I would say that the most important thing about choosing a variable name is:
The name of a variable should be chosen in such a way as to best describe what the value of the variable stands for.
Any other concern is secondary. This means that the best name for a variable within a scope cannot in any way depend on what variables exist in other scopes.
This in turn means: reuse variable names across scopes, it is perfectly fine.
You certainly can do that, as they are in different scopes.
If you want your variables to help explaining the semantics of the surrounding code, you should use appropriately named variables.
If the given variable is just used for counting or similar, then using a general name like 'i' or 'j' in all cases it's an accepted practice.
You should read more about Variable Scope in C++.
You can reuse the variables out of the scope.
There are some naming conventions in programming, google yourself. This is a hit I got from it. Naming conventions are different from language to language, company to company, etc. But most of them have common features such as naming variables to have a meaning.
Remember these naming conventions are there to make our life easier. Using the naming conventions will help to understand your code for another person (or your futureself, someday).
It's always the option you choose, easy way or the (relatively) correct way .

What does putting a structure in an anonymous namespace do? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why are unnamed namespaces used and what are their benefits?
Looking at someones code and this is what they have declared:
namespace {
struct myStruct {
int x;
int y;
} obj1;
}
..in a function I see it used like this:
myStruct& var = obj1;
(Notice namespace is anonymous.)
From how I see it used, I can not figure out why it is declared and used like this.
What does declaring it like this do differently?
Also, why is the pointer created like this rather than the traditional style shown here. i.e. myStruct *ptr;
Thank You!
Everything that's declared inside an anonymous namespace gets a unique, unknowable name, and thus cannot be referred to from any other translation unit. The anonymous namespace is thus guaranteed to be local to the current translation unit only, and never to clash with a different one.
For example, if you say namespace { int i; }, you are guaranteed that only the current translation unit sees the global i. Even if this declaration is in a header that's included in multiple, different TUs, each TU receives its own copy of the global variable (each with a different, unknowable fully-qualified name).
The effect was similar to declaring a global object static (which gives the global object internal linkage) in C++03, where objects in the anonymous namespace may still have external linkage. In C++11, names in an unnamed namespace have internal linkage as per 3.5/4, so the effect is exactly the same for variables and functions as declaring them static – but internal linkage applies to more than just variables and functions (e.g. enums, classes, templates), so as of C++11, you should always prefer unnamed namespaces!
In C++ you are only allowed to have one definition in a given named scope. If there are multiple translation units, you are still only allowed to have one definition but the compiler won't guarantee that all definitions are, indeed, identical. That is, if you need a local type, e.g., a struct or a class you need to make sure that the definition does not conflict with another type anywhere in any other translation unit. Doing this is pretty much impossible in a large project unless you have a way to somehow locally protect your type. This is what an unnamed namespace provides: any name defined within an unnamed namespace is unique within the entire executable.
It does basically the same thing as the static keyword but doesn't actually force internal linkage. The variable is still externally linked, you just have no way of resolving its name in any other translation unit. This was necessary because template arguments must have external linkage, or at least used to require such.
var is also not a pointer, it is a reference. It's not created like other pointers because it is not one.
Also, why is the pointer created like this rather than the traditional style shown here. i.e. myStruct *ptr;
It's a reference, not a pointer, that is created with myStruct& var = obj1; The same rationale applies to pointers, however. A lot of C++ programmers prefer myStruct* ptr over myStruct *ptr, myStruct& ref over myStruct &ref. The compiler doesn't care which you use. This style preference is for the reader of the code.
The reason for putting the asterisk or ampersand with the type rather than the variable is because that asterisk or ampersand is logically a part of the type. The type of ptr is pointer to myStruct. A potential problem arises with this scheme: Type* ptr1, ptr2; Because of rules inherited from C, ptr2 isn't a pointer. It's just an int.
There's an easy solution to this problem. Don't do that! In general, it is better to declare one variable per declaration, with an exception for simple things like int i,j,k; Don't mix pointers and non-pointers.

Why field inside a local class cannot be static?

void foo (int x)
{
struct A { static const int d = 0; }; // error
}
Other than the reference from standard, is there any motivation behind this to disallow static field inside an inner class ?
error: field `foo(int)::A::d' in local class cannot be static
Edit: However, static member functions are allowed. I have one use case for such scenario. Suppose I want foo() to be called only for PODs then I can implement it like,
template<typename T>
void foo (T x)
{
struct A { static const T d = 0; }; // many compilers allow double, float etc.
}
foo() should pass for PODs only (if static is allowed) and not for other data types. This is just one use case which comes to my mind.
Because, static members of a class need to be defined in global a scope, e.g.
foo.h
class A {
static int dude;
};
foo.cpp
int A::dude = 314;
Since the scope inside void foo(int x) is local to that function, there is no scope to define its static member[s].
Magnus Skog has given the real answer: a static data member is just a declaration; the object must be defined elsewhere, at namespace scope, and the class definition isn't visible at namespace scope.
Note that this restriction only applies to static data members. Which means that there is a simple work-around:
class Local
{
static int& static_i()
{
static int value;
return value;
}
};
This provides you with exactly the same functionality, at the cost of
using the function syntax to access it.
Because nobody saw any need for it ?
[edit]: static variables need be defined only once, generally outside of the class (except for built-ins). Allowing them within a local class would require designing a way to define them also. [/edit]
Any feature added to a language has a cost:
it must be implemented by the compiler
it must be maintained in the compiler (and may introduce bugs, even in other features)
it lives in the compiler (and thus may cause some slow down even when unused)
Sometimes, not implementing a feature is the right decision.
Local functions, and classes, add difficulty already to the language, for little gain: they can be avoided with static functions and unnamed namespaces.
Frankly, if I had to make the decision, I'd remove them entirely: they just clutter the grammar.
A single example: The Most Vexing Parse.
I think this is the same naming problem that has prevented us from using local types in template instantiations.
The name foo()::A::d is not a good name for the linker to resolve, so how should it find the definition of the static member? What if there is another struct A in function baz()?
Interesting question, but I have difficulty understanding why you'd want a static member in a local class. Statics are typically used to maintain state across program flow, but in this case wouldn't it be better to use a static variable whose scope was foo()?
If I had to guess why the restriction exists, I'd say it was something to do with the difficulty for the compiler in knowing when to perform the static initialisation. The C++ standards docs might provide a more formal justification.
Just because.
One annoying thing about C++ is that there's a strong dependence on a "global context" concept where everything must be uniquely named. Even the nested namespaces machinery is just string trickery.
I suppose (just a wild guess) that one serious technical issue is working with linkers that were designed for C and that just got some tweak to get them working with C++ (and C++ code needs C interoperability).
It would be nice to be able to get any C++ code and "wrap it" to be able to use it without conflicts in a larger project, but this is not the case because of linkage problems. I don't think there is any reasonable philosophical reason for forbidding statics or non-inline methods (or even nested functions) at the function level but this is what we got (for now).
Even the declaration/definition duality with all its annoying verbosity and implications is just about implementation problems (and to give the ability to sell usable object code without providing the source, something that is now a lot less popular for good reasons).

Is there any reason to use this->

I am programming in C++ for many years, still I have doubt about one thing. In many places in other people code I see something like:
void Classx::memberfunction()
{
this->doSomething();
}
If I need to import/use that code, I simply remove the this-> part, and I have never seen anything broken or having some side-effects.
void Classx::memberfunction()
{
doSomething();
}
So, do you know of any reason to use such construct?
EDIT: Please note that I'm talking about member functions here, not variables. I understand it can be used when you want to make a distinction between a member variable and function parameter.
EDIT: apparent duplicate:
Are there any reasons not to use "this" ("Self", "Me", ...)?
The only place where it really makes a difference is in templates in derived classes:
template<typename T>
class A {
protected:
T x;
};
template<typename T>
class B : A<T> {
public:
T get() {
return this->x;
}
};
Due to details in the name lookup in C++ compilers, it has to be made explicitly clear that x is a (inherited) member of the class, most easily done with this->x. But this is a rather esoteric case, if you don't have templated class hierarchies you don't really need to explicitly use this to access members of a class.
If there is another variable in the same scope with the same name, the this-> will remove the ambiguity.
void Bar::setFoo(int foo)
{
this->foo = foo;
}
Also it makes it clear that you're refering to a member variable / function.
To guarantee you trigger compiler errors if there is a macro that might be defined with the same name as your member function and you're not certain if it has been reliably undefined.
No kidding, I'm pretty sure I've had to do exactly this for that reason!
As "code reason", to distinguish a local parameter or value (that takes precedence) from a member:
class Foo
{
int member;
void SetMember(int member)
{
this->member = member;
}
}
However, that's bad practive to begin with, and usually can be solved locally.
The second reason is more "environment": it sometimes helps Intellisense to filter what I am really looking for. However, I also thing when I use this to find the member I am looking for I should also remove this.
So yes, there are good reasons, but they are all temporary (and bad on the long run).
I can think of readability like when you use additional parenthesis to make things clear.
I think it is mainly as an aid to the reader. It makes it explicit that what is being called is a method on the object, and not an ordinary function. When reading code, it can be helpful to know that the called function can change fields in the current object, for instance.
It's your own choice. I find it more clear when you use this. But if you don't like it, you can ommit it.
This is done to be explicit about the fact that the variable being used is a member variable as opposed to a local or global variable. It's not necessary in most cases, but being explicit about the scope could be helpful if you've trumped the variable with a declaration of the same name in a tighter scope.
At companies I've worked at, we just prepended "m_" to member variables. It can be helpful sometimes, and I much prefer it to using "this->".
Edit:
Adding a link to the GCC docs, which explain a case where using this-> is necessary to get a non-dependent lookup to work correctly.
This is really a matter of style and applies to many other languages such as Java and C#. Some people prefer to see the explicit this (or self, or Me, or whatever) and others do not. Just go with whatever is in your style guidelines, and if it's your project, you get to decide the guidelines.
There are many good answers, but none of them mention that using this-> in source code makes it easier to read, especially when you are reading a code of some long function, but even a short function, imagine a code:
bool Class::Foo()
{
return SomeValue;
}
from looking on this code, you can't clearly know what SomeValue is. It could be even some #define, or static variable, but if you write
bool Class::Foo()
{
return this->SomeValue;
}
you clearly know that SomeValue is a non-static member variable of the same class.
So it doesn't just help you to ensure that name of your functions or variables wouldn't conflict with some other names, but it also makes it easier for others to read and understand the source code, writing a self documenting source code is sometimes very important as well.
Another case, that has arrived on the scenes after C++11 is in lambdas where this is captured.
You may have something like:
class Example
{
int x;
public:
std::function<void()> getIncrementor()
{
return [this] () -> void
{
++(this->x);
}
}
};
Although your lambda is generated within a class, it will only have access to local variables by capturing them (if your compiler does C++14) or capturing this. In the second case, inside the body of lambda, there simply is not x, but only this->x.
I don't think it makes a difference to the compiler, but I always write this-> because I believe it makes the code self-documenting.
Disambiguation: in case you have another similar naming function/variable in the same namespace? I've never seen usage for any other reason.
I prefer it without the explicit this pointer as well. For method calls it doesn't add a lot of value, but it helps distinguish local variables from member variables.
I can't quite remember the exact circumstances, but I've seen (very rare) instances where I had to write "this->membername" to successfully compile the code with GCC. All that I remember is that it was not in relation to ambiguity and therefore took me a while to figure out the solution. The same code compiled fine without using this-> in Visual Studio.
I will use it to call operators implicitly (the return and parameter types below are just dummies for making up the code).
struct F {
void operator[](int);
void operator()();
void f() {
(*this)[n];
(*this)();
}
void g() {
operator[](n);
operator()();
}
};
I do like the *this syntax more. It has a slightly different semantic, in that using *this will not hide non-member operator functions with the same name as a member, though.

Difference between static in C and static in C++??

What is the difference between the static keyword in C and C++?
The static keyword serves the same purposes in C and C++.
When used at file level (outside of a function), it sets the visibility of the item it's applied to. Static items are not visible outside of their compilation unit (e.g., to the linker). Their duration is the same as the duration of the program.
These file-level items (functions and data) should be static unless there's a specific need to access them from outside (and there's almost never a need to give direct access to data since that breaks the central tenet of encapsulation).
If (as your comment to the question indicates) this is the only use of static you're concerned with then, no, there is no difference between C and C++.
When used within a function, it sets the duration of the item. Again, the duration is the same as the program and the item continues to exist between invocations of that function.
It does not affect the visibility of that item since it's visible only within the function. An example is a random number generator that needs to keep its seed value between invocations but doesn't want that value visible to other functions.
C++ has one more use, static within a class. When used there, it becomes a single class variable that's common across all objects of that class. One classic example is to store the number of objects that have been instantiated for a given class.
As others have pointed out, the use of file-level static has been deprecated in favour of unnamed namespaces. However, I believe it'll be a cold day in a certain warm place before it's actually removed from the language - there's just too much code using it at the moment. And ISO C have only just gotten around to removing gets() despite the amount of time we've all known it was a dangerous function.
And even though it's deprecated, that doesn't change its semantics now.
The use of static at the file scope to restrict access to the current translation unit is deprecated in C++, but still acceptable in C.
Instead, use an unnamed namespace
namespace
{
int file_scope_x;
}
Variables declared this way are only available within the file, just as if they were declared static.
The main reason for the deprecation is to remove one of the several overloaded meanings of the static keyword.
Originally, it meant that the variable, such as in a function, would be given storage for the lifetime of the program in an area for such variables, and not stored on the stack as is usual for function local variables.
Then the keyword was overloaded to apply to file scope linkage. It's not desirable to make up new keywords as needed, because they might break existing code. So this one was used again with a different meaning without causing conflicts, because a variable declared as static can't be both inside a function and at the top level, and functions didn't have the modifier before. (The storage connotation is totally lost when referring to functions, as they are not stored anywhere.)
When classes came along in C++ (and in Java and C#) the keyword was used yet again, but the meaning is at least closer to the original intention. Variables declared this way are stored in a global area, as opposed to on the stack as for function variables, or on the heap as for object members. Because variables cannot be both at the top level and inside a class definition, extra meaning can be unambiguously attached to class variables. They can only be referenced via the class name or from within an object of that class.
It has the same meaning in both languages.
But C++ adds classes. In the context of a class (and thus a struct) it has the extra meaning of making the method/variable class members rather members of the object.
class Plop
{
static int x; // This is a member of the class not an instance.
public:
static int getX() // method is a member of the class.
{
return x;
}
};
int Plop::x = 5;
Note that the use of static to mean "file scope" (aka namespace scope) is only deoprecated by the C++ Standard for objects, not for functions. In other words,:
// foo.cpp
static int x = 0; // deprecated
static int f() { return 1; } // not deprecated
To quote Annex D of the Standard:
The use of the static keyword is
deprecated when declaring objects in
namespace scope.
You can not declare a static variable inside structure in C... But allowed in Cpp with the help of scope resolution operator.
Also in Cpp static function can access only static variables but in C static function can have static and non static variables...😊