Can we delete name of a variable in C++? - c++

I want to know if it is possible that for example I defined int temp then later, I define temp as a float.
I mean I want to use the name "temp" more than once in a .cpp file. Is this possible? If it's possible, how?
edit: I meant in the same scope.

No, you can't declare two variables with the same name in the same scope. Their scopes must be different.
Like this:
int temp; // this is global
struct A
{
int temp; // this is member variable, must be accessed through '.' operator
};
int f1()
{
int temp; //local temp, though the global one may by accessed as ::temp
...
}
int f2()
{
int temp; //local
// a new scope starts here
{
int temp; //local, hides the outer temp
...
}
// another new scope, no variable of the previous block is visible here
{
int temp; // another local, hides the outer temp
...
}
}

There is no concept of deleting the name of a variable in C++. However, the lifetime and visibility of automatic variables is limited to the scope that they're declared in. So you could do something like the following:
void foo()
{
{
int temp;
...
}
{
float temp;
...
}
}

It's definitely possible to use the same name for different types and variables within a .cpp file. It can even be done within the same function. The only requirement is that the names be in different scopes.
void LegalExample() {
int temp = 42;
if (...) {
float temp;
...
}
}
void IllegalExample() {
int temp;
float temp;
}
In general though it's considered bad practice to declare variables of the same name within the same function. It usually just leads to developer confusion and places where you really think you need the same named variable twice is typically an indication that you need 2 separate functions

I don't believe that's possible. You could put two variables named temp in different namespaces.
Also you could use Hungarian notation like so:
void foo()
{
float fTemp;
int iTemp;
}

You should avoid this situation, as a variable should do only one thing. Even if you use different scopes over time you might get confused. It is better to define several varibales with different names, instead of reusing one.
Think about what you want to acchieve with this variable and name it correspondingly.

It depends on your scope. You can define a variable name once in a certain scope. You cannot change the type of that variable.
But you can use the same variable name in other scopes for example other methods in your cpp file.

Related

How to implement local variables that can be used in other places with the same conditions in C++

How to get the following code to work?
int main(){
bool flag = true;
if(flag){
// note that I donot want to define variable globally.
int a = 5;
}
if(flag){
// but I still want to use this local variable within the same condition.
a++;
}
}
Note that I don't want to define this variable globally or use a static variable.
I'm curious if there is a way for c++ to make local variables available in all regions with the same conditions?
What you ask for literally is a local variable that is not a local variable. Thats not possible.
On the other hand, you basically want data + code, thats a class. If you wrap it in a class your function can look like this:
int main(){
Foo f;
f.doSomething();
}
And the class can be this
struct Foo {
bool flag = false;
int a = 0;
void doSomething() {
if (flag) ++a;
}
};
What you're directly asking for isn't possible. You'll have to declare something up front. If it's about avoiding construction of objects until you have some relevant detail, you could use std::optional
int main()
{
std::optional<int> a;
if(flag)
{
a = 10;
}
if(a)
{
*a++;
}
}
You set the variable's scope to be the scope you want it to be.
int main(){
bool flag = true;
// declare it in this scope if you want it to persist
// thru this scope
int a;
if(flag){
a = 5;
}
if(flag){
a++;
}
}
No.
According to section 6.4.3, basic.scope.block:
1 Each
(1.1) selection or iteration statement ([stmt.select], [stmt.iter]),
[...]
(1.4) compound statement ([stmt.block]) that is not the compound-statement of a handler
introduces a block scope that includes that statement or handler.
A variable that belongs to a block scope is a block variable.
According to section 6.7.5.4, basic.stc.auto, clause 1:
Variables that belong to a block or parameter scope and are not explicitly declared static, thread_­local, or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

In symbol table how to mark variable out of scope?

I am writing a toy compiler, which compile a c/c++ like language to c++.
I am using bison, but in this structure is hard to handle when variable became out of scope.
In the source lanugage in the whole main function there can be only one variable with the same name, it is good, but there is a problem what I cannot solve.
I cannot make c++ code like this, because c++ compiler throw semantical error:
'var' was not declared in this scope.
int main()
{
if (true)
{
int var = 4;
}
if (true)
{
var = 5;
}
}
The source language has while, if and if/else statements.
I have to throw semantical error if a declared variable is assinged in out of scope.
For example:
This should be semantical error, so I cannot generetad this code:
int main()
{
while(0)
{
int var = 1;
}
if (1)
{
var = 2;
}
}
This also have to be semantical error:
int main()
{
if (0)
{
int var = 1;
}
else
{
if (1)
{
var = 5;
}
}
}
And this is allowed, I can generate this code:
int main()
{
if (0)
{
}
else
{
int var = 1;
if (1)
{
while (0)
{
while (0)
{
var = 2;
}
}
}
}
}
I tried lot of things, but I cannot solve when there is nested if, if/else or while.
I read tons of tutorials about symbol table, but none of them can explain properly how to manage a variable if it is become out of scope.
If you familiar with this topic and with bison, please do not just give me hints, like "use stack, and mark a variable if it become out of scope". I found lot of article about it.
Instead of please give me pseudocode or concrate implementation sketch.
I think it cannot be so much difficult, because in the whole main function there can be one variable with the same name as I wrote.
Symbol table:
struct SymbolType
{
int lineNumber;
std::string identifier;
int identifierValue;
Type type;
int functionArgumentNumber;
Type functionReturnType;
Type markType;
bool outOfScope;
};
class Symbol
{
public:
void AddVariable(int _lineNumber, std::string _identifier, int _identifierValue, Type _type, int _functionArgumentNumber, Type _functionReturnType, Type _markType, bool _outOfScope);
void AddMarker(int _lineNumber, std::string _scopeName, Type _markType);
bool FindVariable(std::string _identifier);
int FindVariableValue(std::string _identifier);
void Remove();
void Print();
std::vector<SymbolType> symbolTable;
private:
int lineNumber;
std::string identifier;
int identifierValue;
Type type;
int functionArgumentNumber;
Type functionReturnType;
Type markType;
bool outOfScope;
};
Now let's assume the following: While you are in a nested scope you cannot add a variable to a parent scope. So we can work e.g. with a stack like structure (push/pop at the end only suffices, but with read access to all entries – the latter requirement disqualifying std::stack, so we'd operate e.g. on std::vector instead).
Encountering the declaration of a new variable:Run up the entire stack to see if that variable exists already. If so, issue an error ('duplicate declaration/definition').
Encountering accessing a variable: Run up the entire stack to see if that variable exists; if not, issue an error ('not declared/defined' – I wouldn't differentiate between the variable not having been defined ever or having left the scope).
On leaving a scope, run up the stack and remove any variable that resides in that scope.
To be able to do 3. you have (at least) two options:
With every stack entry provide an identifier for the respective scope, could be simple counter. Then delete all those variables that have the same counter value. If you fear the counter might overflow, then reduce it by 1 as well (then it would always represent current scope depths).
Have a sentinel type – that one would be pushed to the stack on opening a new scope, compare unequal to any variable name, and on leaving a scope you'd delete all variables until you encounter the sentinel – and the sentinel itself.
This processing makes your outOfScope member obsolete.
Your addVariable function takes too many parameters, by the way – why should a variable need a return type, for instance???
I recommend adding multiple functions for every specific semantic type your language might provide (addVariable, addFunction, ...). Each function accepts what actually is necessary to be configurable and sets the rest to appropriate defaults (e.g. Type to Function within addFunction).
Edit – processing the example from your comment:
while(condition)
{ // opens a new scope:
// either place a sentinel or increment the counter (scope depth)
int var = 1; // push an entry onto the stack
// (with current counter value, if not using sentinels)
if (true)
{ // again a new scope, see above
var = 2; // finds 'var' on the stack, so fine
} // closes a scope:
// either you find immediately the sentinel, pop it from the stack
// and are done
//
// or you discover 'var' having a counter value less than current
// counter so you are done as well
} // closing next scope:
// either you find 'var', pop it from the stack, then the sentinel,
// pop it as well and are done
//
// or you discover 'var' having same counter value as current one,
// so pop it, then next variable has lower counter value again or the
// stack is empty, thus you decrement the counter and are done again

How to make functions variables public, they are not in a class C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 months ago.
I would like to know how I can make a function's variable public to other functions.
Example:
void InHere
{
int one = 1; // I want to be public
}
int main()
{
InHere(); // This will set int one = 1
one = 2; // If the variable is public, I should be able to do this
return 0;
}
Does anyone know how to do this? The only things I find when searching is for classes, as you can see nothing is in a class and I don't want them to be in one.
Any help is really appreciated!
A variable defined locally to a function is generally inaccessible outside that function unless the function explicitly supplies a reference/pointer to that variable.
One option is for the function to explicitly return a reference or pointer to that variable to the caller. That gives undefined behaviour if the variable is not static, as it does not exist after the function returns.
int &InHere()
{
static int one = 1;
return one;
}
void some_other_func()
{
InHere() = 2;
}
This causes undefined behaviour if the variable one is not static since, as far as the program as a whole is concerned, the variable only comes into existence whes InHere() is called and ceases to exist as it returns (so the caller receives a dangling reference - a reference to something that no longer exists).
Another option is for the function to pass a pointer or reference to the variable as an argument to another function.
void do_something(int &variable)
{
variable = 2;
}
int InHere()
{
int one = 1;
do_something(one);
std::cout << one << '\n'; // will print 2
}
The downside is that this only provides access to functions CALLED BY InHere(). Although the variable does not need to be static in this case, the variable still ceases to exist as InHere() returns (so if you want to combine option 1 and option 2 in some way, the variable needs to be static)
A third option is to define the variable at file scope, so it has static storage duration (i.e. its lifetime is not related to the function);
int one;
void InHere()
{
one = 1;
}
void another_function()
{
one = 2;
}
int main()
{
InHere();
// one has value 1
some_other_function();
// one has value 2
}
A global variable can be accessed in any function that has visibility of a declaration of the variable. For example, we could do
extern int one; // declaration but not definition of one
int one; // definition of one. This can only appear ONCE into the entire program
void InHere()
{
one = 1;
}
And, in other source file
extern int one; // this provides visibility to one but relies on it
// being defined in another source file
void another_function()
{
one = 2;
}
int main()
{
InHere();
// one has value 1
some_other_function();
// one has value 2
}
Be careful with that though - there are numerous down-sides of global/static variables, to the extent they are usually considered VERY BAD programming technique. Have a look at this link (and pages linked to from there) for a description of some of the problems.
Just set the variable as a global variable. Then you can access it from other functions.
int one;
void InHere()
{
one = 1; // I want to be public
}
int main()
{
InHere(); // This will set int one = 1
one = 2; // If the variable is public, I should be able to do this
return 0;
}
if you want it inside a class, then try the code below
#include <iostream>
using namespace std;
class My_class
{
// private members
public: // public section
// public members, methods or attributes
int one;
void InHere();
};
void My_class::InHere()
{
one = 1; // it is public now
}
int main()
{
My_class obj;
obj.InHere(); // This will set one = 1
cout<<obj.one;
obj.one = 2; // If the variable is public, I should be able to do this
cout<<obj.one;
return 0;
}

Do functions have access to variables in the immediate outer scope without parameter input to the function in C++?

Do functions have access to variables in the immediate outerscope without parameter input to the function in C++?
=========
Here is a code I am working on
#include...
void ReadGrid();
void SaveGrid();
int main(){
ReadGrid();
}
void ReadGrid() {
int m=1;
int n[]={1,2,3};
vector<int> o(3,10);
SaveGrid();
}
void SaveGrid() {
int a=m;
int b=n[1];
int c=o[1];
}
Why can't I access the variables in the ReadGrid() functions in SaveGrid(), doesn't the local scope of SaveGrid() treat the scope of ReadGrid() as Global when SaveGrid() is called?
Your question might be better formed thus:
When function a() calls function b(), does b() automatically get visibility into all of a()'s local variables?
And the answer is … no. They are still different block scopes, regardless of your call stack.
Each set of braces denotes a separate scope, so if you create a block with braces, and declare variables inside them, they will not be viisble outside of it. If you create nested blocks of braces, they have inner block has access to the outer block, but not the other way around.
This also applies not only to function (which always have their scope), but also to blocks inside a function as well.
i.e. Two different variables named i, no nameclash because of different scopes:
{
int i;
}
{
int i;
}
Here we have access.
{
int i;
{
int x = i; <== in scope
}
int y = x; <== error
}
If you want to have a set ov variables assoicated to some logical function, then you should put them inside a class or struct.
No, but this is where objects can come into play, e.g. in this pseudo code they share the same data:
class Grid {
private:
int m;
int n[];
vector<int> o;
public:
void ReadGrid(){
// get m,n, and o
}
void SaveGrid() {
// put m,n, and o
}
}
int main(){
Grid grid;
grid.ReadGrid();
}
No what are trying to do is illogical.
If you want the value of m to be available to both ReadGrid and SaveGrid then you must defint "m" as a global variable and you can initialise it in ReadGrid and use the same value in SaveGrid.
Here is a snippet, for your reference
#include...
void ReadGrid();
void SaveGrid();
int m;// global variable
int n[];//global variable
int main(){
ReadGrid();
}
void ReadGrid() {
m=1;
n[]={1,2,3};
SaveGrid();
}
void SaveGrid() {
int a=m;
int b=n[1];
}

Handling lots of variable declarations

I am implementing a class and I have a function that does things using lots of variables that need to be declared and initialised.
I'd like the variable declarations not to clutter the function and do something like:
doFunction(){
declare();
//Do things with variables declared in declare()
}
void declare(){
//declare lots of variables here
}
This does not work as the variables are scoped to declare() and aren't seen by doFunction(). What's a sensible way to handle this problem?
Since each of the variables that you declare must be assigned a value, you should combine declaration with initialization. In other words, instead of
int x;
double y;
std::string z;
x = 1;
y = 2.0;
z = "3";
do this:
int x = 1;
double y = 2.0;
std::string z("3");
This is pretty much as far as you can push this approach with locals: declaring variables is an essential part of the function body, you cannot (and arguably, should not) move it to a remote location.
You can also move the member function into a nested private class, move the local variables into the class, and do calculations there:
class specialCalc {
int x;
double y;
std::string z;
specialCalc() : x(1), y(2.0), z("3") {}
public:
int calculate() {
...
}
};
void doFunction() {
specialCalc calc;
cout << calc.calculate() << endl;
}
PS: I am deliberately not mentioning preprocessor-based solutions because they would negatively impact readability.
I'm not really advocating this, but:
struct Declare
{
int x;
float y;
char z;
vars() :x(1),y(3.14),z('z') {}
};
void doFunction()
{
Declare vars;
// use vars.x, vars.y and vars.z as your variables
}
You have a number of choices:
1) Get over it. If you need lots of variables, you'll need to suffer the fact they need to be declared somewhere.
2) Put them into a class or in a structure as a member variable so you can declare them in the .h file and they'll be invisible in the .C/.cpp file.
3) Aggregate them into an array, and declare only the array and initialize them in a for() loop or something. This really only works if they're all a similar type and you don't do silly things like "index 4" is my "counter object for this", and "index 5" is my "thing I'm going to print to the screen" as then you loose the name associated with the variable itself, which is rather helpful when reading the code later (of course).
4) put them in a define statement somewhere else:
#define MYVARS int a; char b[1024]; ...
void funstuff() {
MYVARS
}
5) Modify an IDE so that it can hide/collapse the variable declarations when you're viewing the code.
Note that of all of these choices, number 1 is still probably the right answer :-)