As the title suggest how can i declare a variable inside loop and use it outside?
EXAMPLE
void Function(String s)
{
for(i = 0; s[i] != '\0'; ++i)
{
switch(s[i])
{
case 'i':int x;
case 'd':double x;
case 'c':char x;
}//end of switch
}//end of for loop
//now i want to use 'x' here,i.e.,out side the loop how will i do it?
}//end of void function
EDIT I know the scope thing but i saw some one achieving this with template class/function but I dont know how to use template class/func to do this..so anyone knows?
{ } - are scope delimiters, anything you define inside it, cannot be access outside. So if you want, you can declare it outside loop and then you can access it outside as well as inside loop.
No. Simplified, that's what a scope is - the scope within which declared variables are accessible.
You need to declare the variable in the outer scope if you want to access it from there:
{
int x = 0;
for (...)
{
x= 1;
}
if (x ==1)
{
printf("it works");
}
}
Related
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.
I'm currently trying to make an enemy in a game. The Enemy is meant to move towards the player using the player position (x and y coordinate) and comparing it to the enemy's coordinates. however I seem to be having problems with the identifiers.
void DinoEnemy::Update()
{
DinoEnemy GetPosition(int& dinox, int& dinoy); ///calling a function that should return dinox and diny
m_AnimatedSprite.SetCurrentAnimation(E_DinoState_Hatching);
GameStateManager* pGameStateManager = C_SysContext::Get<GameStateManager>();
GameState* pCurrentGameState = pGameStateManager->GetCurrentGameState();
GameObject* PlayerPos = pCurrentGameState->GetPlayer();
if (PlayerPos)
{
int playerposX = 0;
int playerposY = 0;
PlayerPos->GetPosition(playerposX, playerposY);
}
if (dinox << playerposX) ///Here is where the error is.
{
dinox++;
}
}
dinox and playerposX are undeclared in the final if statement
Thanks in advance ;u;
That's not how you call a function
You have
DinoEnemy GetPosition(int& dinox, int& dinoy);
But that's no function call as your comment suggests, but a function declaration. You meant to declare two variables, then call the function (as you did later on in your code, so why do it wrong here?):
int dinox;
int dinoy;
GetPosition(dinox, dinoy);
Beware: If GetPosition reads from dinox and dinoy you must intialize the values, but it seems like it only writes them.
The scope of playerposX is wrong
The variables playerposX and playerposY are only visible inside the if-block, simply declare them outside of it:
int playerposX = 0;
int playerposY = 0;
if (PlayerPos)
{
PlayerPos->GetPosition(playerposX, playerposY);
}
There should probably be an else that handles the case when PlayerPos == nullptr. After all it doesn't make sense to compare the players position to something if the player doesn't have any position.
Little typo
if (dinox << playerposX)
Here you probably don't want a bitshift (<<) but rather a smaller-than-comparison (<).
There will be an issue with the scope of playerposX. Since it is declared inside the if block, it gets out of scope outside of the if block.
Additionally, in case PlayerPos cannot be translated to true, e.g., if it is NULL, playerposX will never be declared at all.
You may want to declare playerposX outside of the if block. Or add the second if block within the scope of the first.
In other words
if (PlayerPos)
{
int playerposX = 0;
int playerposY = 0;
PlayerPos->GetPosition(playerposX, playerposY);
if (dinox << playerposX)
{
dinox++;
}
}
It acts like this.
fun();//return 1;
for (int i=0;i++;i<100)
fun();//return 2;
fun();//return 3;
I don't want to do it manually, like:
static int i=0;
fun(){return i};
main()
{
i++;
fun();//return 1;
i++;
for (int i=0;i++;i<100)
fun();//return 2;
i++;
fun();//return 3;
}
New classes and static variables are allowed.
I am trying to design a cache replacement algorithm. Most of the time I use the LRU algorithm, but, if I use LRU algorithm inside a loop I would very likely get a cache thrashing.
https://en.wikipedia.org/wiki/Thrashing_(computer_science)
I need to know if I am inside a loop. Then I can use the LFU algorithm to avoid thrashing.
An obvious way of doing this would be using the __LINE__ macro. It will return the source code line number, which will be different throughout your function.
It is not possible within c++ for a function to know whether or not it is inside a loop 100% of the time. However, if you are happy to do some manual coding to tell the function that it is inside a loop then making use of C++'s default parameters you could simply implement a solution. For more information on default parameters see http://www.learncpp.com/cpp-tutorial/77-default-parameters/. Also, because Global variables are generally frowned upon I have placed them in a separate namespace in order to prevent clashes.
namespace global_variables {
int i = 0;
}
int func(bool is_in_loop = false) {
if (is_in_loop)
{
//do_something;
return global_variables::i;
}
else
{
//do_something_else;
return global_variables::i++;
}
}
int main()
{
// Calling function outside of loop
std::cout << func();
// Calling function inside of loop
for (int j=0;j<100;j++)
{
// is_in_loop will be overided to be true.
std::cout << function(true);
}
return 0;
}
I'm still relatively new to C++ and I know this might be a rather silly question but is there any way to share a local variable value from one function to another of a different class? Or somehow point a global variable to a function variable using the dereference operator *? Simply put, I need to access local variables of one function and utilize their values in another function of a different class.
For instance:
void CClassX::MyFunction1(){
int x = 8;
}
void CClassY::MyFunction2()
{
x; //utilize x in some way
for(int i; i<x; i++){}
}
Thanks for any comments...
Yes You can do this by sending the variable by reference.And send variable to that particular function in which you want to access.
**void CClassX::MyFunction1()
{
int x = 8;
CClassY::MyFunction2(x)
}
void CClassY::MyFunction2(int &x)
{
x; //utilize x in some way
for(int i; i<x; i++)
{}
}
Once I assumed that these two have the same meaning but after reading more about it i'm still not clear about the difference. Doesn't the local scope sometimes refer to scope of function?
and what does it mean that only labels have a function scope?
void doSomething()
{ <-------
{ <---- |
| |
int a; Local Scope Function Scope
| |
} <---- |
} <-------
Function Scope is between outer { }.
Local scope is between inner { }
Note that, any scope created by {``} can be called as the local scope while the {``} at the beginning of the function body create the Function scope.
So, Sometimes a Local Scope can be same as Function Scope.
what does it mean that only labels have a function scope?
Labels are nothing but identifiers followed by a colon. Labeled statements are used as targets for goto statements. Labels can be used anywhere in the function in which they appear, but cannot be referenced outside the function body. Hence they are said to have Function Scope.
Code Example:
int doSomething(int x, int y, int z)
{
label: x += (y + z); /* label has function scope*/
if (x > 1)
goto label;
}
int doSomethingMore(int a, int b, int c)
{
if (a > 1)
goto label; /* illegal jump to undefined label */
}
Local scope is the area between an { and it's closing }. Function scope is the area between the opening { of a function and its closing }, which may contain more "local" scopes. A label is visible in the entirety of the function within which it is defined, e.g.
int f( int a )
{
int b = 8;
if ( a > 14 )
{
int c = 50;
label:
return c - a - b;
}
if ( a > 7 ) goto label;
return -99;
}
int c is not visible outside its enclosing block. label is visible outside its enclosing block, but only to function scope.
Doesn't the local scope sometimes refer to scope of function?
Yes. In most C-derived languages, variables are valid in the scope in which they're declared. If you declare a variable inside a function, but not within any other code block, then that variable is usually called a "local" or "automatic" variable. You can refer to it anywhere in the function. On the other hand, if you declare your variable inside another code block -- say, in the body of a conditional statement, then the variable is valid only inside that block. Several other answers here give good examples.
and what does it mean that only labels have a function scope?
Context would be helpful, but it means that you can't jump from one function to a label in a different function.
void foo(int a) {
if (a == 0) goto here; // okay -- 'here' is inside this function
printf("a is not zero\n");
goto there; // not okay -- 'there' is not inside this function
here:
return;
}
void bar(int b) {
if (b == 0) goto there; // okay -- 'there' is in this function
printf("b is not zero\n");
there:
return;
}
Not to stir up a hornet's nest, but the scope of labels probably won't come up too often. Labels are mainly useful with the goto statement, which is needed only very rarely if ever, and even if you did choose to use goto you probably wouldn't even think of trying to jump into a different function.
The scope of the function is slightly larger than the scope of the function body: The function arguments are in the outer scope, while local variables are only in the inner one. This is most visibly manifest in a function-try-block:
void f(int a) try {
// function body
} catch(...) {
// catch block
}
Inside the catch block, only the variables in function scope are still in scope, but not the local variables.
Of course you can and do also introduce further, deeper nested scopes all the time, e.g. in for loop bodies or conditional bodies.
bool m[3][3];
void f1()
{
int i;
// redefining a variable with the same name in the same scope isn't possible
//int i; //error C2086: 'int i' : redefinition
}
void f2()
{
int i; // ok, same name as the i in f1(), different function scope.
{
int i; // ok, same name as the i above, but different local scope.
}
// the scope if the following i is local to the for loop, so it's ok, too.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (m[i][j])
goto loopExit;
}
}
loopExit:
std::cout << "done checking m";
// redefining a label with the same name in the same function isn't possible
// loopExit:; // error C2045: 'loopExit' : label redefined
}
void f3()
{
loopExit:; // ok, same label name as in f2(), but different function scope
}