c++11 capture-by-value lambda producing wrong value - c++

I'm trying to store a lambda in an object system involving several layers of indirection. I'm using g++ 4.7.1.
Depending on how exactly I construct the (equivalent) objects, the lambda may or may not have the correct value.
Code:
#include <iostream>
#include <functional> // used for std::function
using namespace std; // TODO nope
typedef function<int()> intf;
struct SaveLambda {
const intf func;
SaveLambda(const intf& _func) : func(_func) {}
};
struct StoreSaved {
const SaveLambda* child;
StoreSaved(const SaveLambda& _child) : child(&_child) {
cout << "Before returning parent: " << child->func() << endl;
}
};
int main() {
const int ten = 10;
auto S = SaveLambda([ten](){return ten;});
cout << "No indirection: " << S.func() << endl << endl;
auto saved = StoreSaved(S);
cout << "Indirection, saved: " << saved.child->func() << endl << endl;
auto temps = StoreSaved ( SaveLambda([ten](){cout << "&ten: "<< &ten << endl; return ten;}) );
cout << "***** what. *****" << endl;
cout << "Indirection, unsaved: " << temps.child->func() << endl;
cout << "***** what. *****" << endl << endl;
cout << "ten still lives: " << ten << endl;
}
Compile as g++ -std=c++11 -Wall -o itest itest.cpp and run: notice the one line of output with a different value.
What am I doing wrong? I assumed that capture-by-value would, well, capture by value. (Observe most disconcertingly that the print in StoreSaved (line 15) produces the correct value, unlike line 34, despite these both referring to the same object. The only difference is adding another layer of indirection.)

This is wrong:
auto temps = StoreSaved(
/* This temporary value dies at the last semicolon! */
SaveLambda([ten](){cout << "&ten: "<< &ten << endl; return ten;})
);
StoreSaved then has a pointer to a nonexistent object. Using it is UB.

As already pointed out by others, the problem is that in temps you end with a pointer to a nonexistent SaveLambda struct, as it is a temporary.
You can keep a copy using a SaveLambda struct in StoreSaved, instead of a pointer:
struct StoreSaved {
const SaveLambda child;
StoreSaved(const SaveLambda& _child) : child(_child) {
cout << "Before returning parent: " << child.func() << endl;
}
};
You also have to change all the child->func() to child.func(), as you are not dealing with a pointer anymore.

Related

Difference in the usage of function prototype with / without pointers

I'm following simple C++ tutorial.
#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 2;
cout << "Before swapping " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(a,b);
cout << endl;
cout << "After swapping " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int &n1, int &n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
The above code works fine (both g++ and icc), but if I were to use pointers in the functions the code fails if I do not include the prototype at the head of the program.
#include <iostream>
using namespace std;
void swap(int*, int*); // The code fails if I comment this line.
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << endl;
cout << "After swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
As far as I know, C++ compiling process is top-bottom, so the 2nd code seems more reasonable in which the information of the function is provided before int main() is encountered. My question is, why the 1st code works fine even without the knowledge of function before int main()?
The issue with the first program is you're not actually calling your own swap function. At the top of the file, you have:
using namespace std;
which brings std::swap into scope and that's the function that you're actually calling. If you put a cout statement in your own swap you'll see that it's never actually called. Alternatively, if you declare your swap before main, you'll get an ambiguous call.
Note that this code is not required to behave like this, since iostream doesn't necessarily bring std::swap into scope, in which case you'll get the error that there is no swap to call.
In the second program, the call to swap(&a, &b) fails because there is no overload of std::swap that accepts 2 temporary pointers. If you declare your swap function before the call in main, then it calls your own function.
The real bug in your code is the using namespace std;. Never do that and you'll avoid issues of this nature.
The reason why the first version works is because it doesn't call your swap(...) function at all. The namespace std provides - Edit: depending on the headers you (and the standard headers themselves) include - swap(...) functions for various types and integers are one of them. If you would remove using namespace std you would have to type std::swap(...) to achieve the same effect (same goes for std::cout, std::endl).
That's one reason why using namespace is a double-edged sword for beginners in my opinion but that's another topic.
Your code is fine; but you're right, it fails if you comment on the line you point to.
But actually, as the others tell you, there is a Swap function in c ++, so it doesn't matter if you create a prototype of the function and do it later because the compiler calls its own swap function.
But since swap works for any data type, except for pointers, then you will understand the reason for your problem, since in this case you do have to create your own swap function that accepts pointers as parameters.
Just move your function above main to make it work correctly, nothing more:
#include <iostream>
using namespace std;
//void swap(int*, int*); // The code fails if I comment this line.
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << endl;
cout << "After swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

Spurious Characters generated from templated Child T cast from Parent base in vector [duplicate]

This question already has answers here:
What is object slicing?
(18 answers)
Closed 3 years ago.
I'm using a pattern of assigning a base class to a templated class so that I can put different types in a vector, vis-a-vis Attribute<String> and Attribute<int>, and the reason for this is that I want a vector containing different objects that inherit the same base object.
The problem that I am getting of spurious text being generated relates to the output that is generated once the Base object is retrieved from the vector and cast back to the original Attribute template object.
Problem Output, using inline comments to show where output differed from expectation:
T (String)
ID: Id-1
Key: -�'��,�'�8���Id-1 // expected key1
Value: // expected one
T (String)
ID: Id-2
Key: -�'��,�'�8���Id-2 // expected key2
Value: // expected two
T (String)
ID: Id-3
Key: -�'��,�'�8���Id-3 // expected key3
Value: // expected three
T (int)
ID: Id-4
Key: -�'��,�'�8���Id-4 // expected key4
Value: 0 // expected 4
T (String)
ID: Id-5
Key: -�'�-�'�8���Id-5 // expected key5
Value: // expected 5
T (int)
ID: Id-6
Key: -�'�0-�'�8���Id-6 // expected key6
Value: 0 // expected 6
Here is the reproducible example, I've added a Makefile which uses the c++ compiler instead of g++ compiler as on Mac (where I am doing this) C++17 isn't fully implemented yet.
harness.cpp
#include <iostream>
#include "Attribute.h"
#include <vector>
using namespace std;
using String = std::string;
int main()
{
// TEST THE Attribute CLASS BY ITSELF
Attribute <String> att("testkey","testvalue", TypeRef::String, "testId");
cout << "Key: "+att.getKey() << endl;;
cout << "Value: "+att.getValue() << endl;
cout << "Id: "+att.getId() << endl;
cout << endl;
/* Output:
Key: testkey
Value: testvalue
Id: testId
*/
// TEST SIX INSTANCES OF Attribute CLASS BEFORE ADDING TO vector
std::vector<AttributeObject> vector;
Attribute<String> q("key1","one",TypeRef::String, "Id-1"); AttributeObject &qBase = q;
cout << "T (String)" << endl;
cout << "Id1: " << q.getId() << endl;
cout << "Key1: " << q.getKey() << endl;
cout << "Value1: " << q.getValue() << endl;
cout << endl;
Attribute<String> w("key2","two",TypeRef::String, "Id-2"); AttributeObject &wBase = w;
cout << "T (String)" << endl;
cout << "Id2: " << w.getId() << endl;
cout << "Key2: " << w.getKey() << endl;
cout << "Value2: " << w.getValue() << endl;
cout << endl;
Attribute<String> e("key3","three",TypeRef::String, "Id-3"); AttributeObject &eBase = e;
cout << "T (String)" << endl;
cout << "Id3: " << e.getId() << endl;
cout << "Key3: " << e.getKey() << endl;
cout << "Value3: " << e.getValue() << endl;
cout << endl;
Attribute<int> r("key4",4,TypeRef::Int, "Id-4"); AttributeObject &rBase = r;
cout << "T (int)" << endl;
cout << "Id4: " << r.getId() << endl;
cout << "Key4: " << r.getKey() << endl;
cout << "Value4: " << r.getValue() << endl;
cout << endl;
Attribute<int> t("key5",5,TypeRef::String, "Id-5"); AttributeObject &tBase = t;
cout << "T (int)" << endl;
cout << "Id5: " << t.getId() << endl;
cout << "Key5: " << t.getKey() << endl;
cout << "Value5: " << t.getValue() << endl;
cout << endl;
Attribute<int> y("key6",6,TypeRef::Int, "Id-6"); AttributeObject &yBase = y;
cout << "T (int)" << endl;
cout << "Id6: " << y.getId() << endl;
cout << "Key6: " << y.getKey() << endl;
cout << "Value6: " << y.getValue() << endl;
cout << endl;
cout << endl;
/* Output:
T (String)
Id1: Id-1
Key1: key1
Value1: one
T (String)
Id2: Id-2
Key2: key2
Value2: two
T (String)
Id3: Id-3
Key3: key3
Value3: three
T (int)
Id4: Id-4
Key4: key4
Value4: 4
T (int)
Id5: Id-5
Key5: key5
Value5: 5
T (int)
Id6: Id-6
Key6: key6
Value6: 6
*/
vector.push_back(qBase);
vector.push_back(wBase);
vector.push_back(eBase);
vector.push_back(rBase);
vector.push_back(tBase);
vector.push_back(yBase);
// TEST ALL Attribute CLASS INSTANCES AS EXTRACTED FROM A vector
int x = 0;
for (AttributeObject baseObject : vector) {
TypeRef typeRef = baseObject.getTypeRef();
if(typeRef == TypeRef::String)
{
cout << endl;
cout << "T (String)" << endl;
Attribute <String> *pChild = (Attribute <String> *) &baseObject;
cout << "ID: " << pChild->getId() << endl;
const String sKey = pChild->getKey();
cout << "Key: " << sKey << endl;
const String sValue = pChild->getValue();
cout << "Value: " << sValue << endl;
}
else if(typeRef == TypeRef::Int)
{
cout << endl;
cout << "T (int)" << endl;
Attribute <int> *pChild = (Attribute <int> *) &baseObject;
cout << "ID: " << pChild->getId() << endl;
const String sKey = pChild->getKey();
cout << "Key: " << sKey << endl;
const int iValue = pChild->getValue();
cout << "Value: " << (int)iValue << endl;
}
x++;
}
/* Output (with differing expected values added as inline comments)
T (String)
ID: Id-1
Key: -�'��,�'�8���Id-1 // expected key1
Value: // expected one
T (String)
ID: Id-2
Key: -�'��,�'�8���Id-2 // expected key2
Value: // expected two
T (String)
ID: Id-3
Key: -�'��,�'�8���Id-3 // expected key3
Value: // expected three
T (int)
ID: Id-4
Key: -�'��,�'�8���Id-4 // expected key4
Value: 0 // expected 4
T (String)
ID: Id-5
Key: -�'�-�'�8���Id-5 // expected key5
Value: // expected 5
T (int)
ID: Id-6
Key: -�'�0-�'�8���Id-6 // expected key6
Value: 0 // expected 6
*/
return 0;
}
Attribute.cpp (here just for the sake of the Makefile because the c++ complier generates a nasty warning if you don't use a .cpp file):
#include "Attribute.h"
Attribute.h:
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
using String = std::string;
enum class TypeRef {
String,
Int
};
class AttributeObject{
public:
AttributeObject() {}
AttributeObject(TypeRef typeRef, String Id) : typeRef(typeRef), id(Id) {}
TypeRef getTypeRef()
{
return this->typeRef;
}
String getId()
{
return this->id;
}
protected:
TypeRef typeRef;
String id;
};
template<class T>
class Attribute : public AttributeObject {
public:
using value_type = T;
Attribute(const String& Key, const T& Value, const TypeRef& TypeRef, const String& Id) :
AttributeObject(TypeRef, Id),
key(Key),
value(Value)
{}
String const& getKey() const {
return key;
};
T const& getValue() const {
return value;
}
TypeRef const& getTypeRef() const {
return typeRef;
}
private:
String key;
T value;
};
Makefile:
CC=c++
FLAGS=-c -g -std=c++17
All: build
mkdirs:
# In mkdirs:
mkdir -p obj
build: clean mkdirs harness.o Attribute.o
# In build:
$(CC) obj/harness.o obj/Attribute.o -o harness
ls
harness.o: harness.cpp
# harness.o:
$(CC) $(FLAGS) harness.cpp -o obj/harness.o
ls obj
Attribute.o: Attribute.cpp
$(CC) $(FLAGS) Attribute.cpp -o obj/Attribute.o
ls obj
clean:
# In clean:
rm -rf obj
ls
Kind regards.
As mentioned in the comments, the biggest problem in this code is object slicing and to work around that you should use base class pointers or references. In a vector you can store pointers but not real references (you can use std::reference_wrapper though).
You have to decide if the vector should own the objects or if it should only keep pointers to objects whos lifespan is controlled separately from the vector.
std::vector<BaseClass*> v1; // objects will live on even when the vector is destroyed
std::vector<std::unique_ptr<BaseClass>> v2; // objects are destroyed if the vector is destroyed
In your test code, you've used the first option so I'll go with that, but it's easy (and often preferable) to change that.
Here's an idea of how to make the changes needed. I hope the comments in the code explains most of it.
Attribute.h
// add a header guard to not accidentally include it into the same translation unit more than once
#ifndef ATTRIBUTE_H
#define ATTRIBUTE_H
#include <iostream>
#include <string>
#include <typeinfo> // typeid()
using String = std::string;
// An abstract base class for all Attribute<T>'s
// Since "key" is common for them all, I've put it in here.
class AttributeBase {
public:
AttributeBase(const String& k) : key(k) {}
virtual ~AttributeBase() = 0; // pure virtual
String const& getKey() const {
return key;
};
// all descendants must implement a print method
virtual std::ostream& print(std::ostream&) const = 0;
// trust all Attribute<T>'s to get direct access to private members
template<typename T>
friend class Attribute;
private:
String key;
};
// AttributeBase is an abstract base class but with a default
// destructor to not force descendants to have to implement it.
AttributeBase::~AttributeBase() {}
// streaming out any AttributeBase descendant will, via this method, call the virtual
// print() method that descendants must override
std::ostream& operator<<(std::ostream& os, const AttributeBase& ab) {
return ab.print(os);
}
template<class T>
class Attribute : public AttributeBase {
public:
using value_type = T;
Attribute(const String& Key, const T& Value) :
AttributeBase(Key),
value(Value)
{}
T const& getValue() const {
return value;
}
std::ostream& print(std::ostream& os) const override {
// Print an implementation defined name for the type using typeid()
// and then "key" and "value".
// Direct access to "key" works because of the "friend"
// declaration in AttributeBase. We could have used getKey()
// though, but this shows one use of "friend".
return
os << "type: " << typeid(value).name() << "\n"
<< "key: " << key << "\n"
<< "value: " << value << "\n";
}
private:
T value;
};
// end of header guard
#endif
harness.cpp
// include your own headers first to catch include chain errors more easily
#include "Attribute.h"
#include <iostream>
#include <vector>
#include <memory>
// using namespace std; // bad practice:
// https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
using String = std::string;
int main()
{
// TEST THE Attribute CLASS BY ITSELF
// in the following functions we're using the added operator<< to let the objects
// print their own values
Attribute <String> att("testkey","testvalue");
std::cout << "-- att --\n" << att << "\n";
// TEST SIX INSTANCES OF Attribute CLASS BEFORE ADDING TO attvec
// use base class pointers to avoid slicing
std::vector<AttributeBase*> attvec;
Attribute<String> q("key1","one");
std::cout << "-- q ---\n" << q << "\n";
Attribute<String> w("key2","two");
std::cout << "-- w ---\n" << w << "\n";
Attribute<String> e("key3","three");
std::cout << "-- e --\n" << e << "\n";
Attribute<int> r("key4",4);
std::cout << "-- r --\n" << r << "\n";
Attribute<int> t("key5",5);
std::cout << "-- t --\n" << t << "\n";
Attribute<int> y("key6",6);
std::cout << "-- y --\n" << y << "\n";
// added a 7:th object with a different type
Attribute<double> u("key7", 7.12345);
std::cout << "-- u --\n" << u << "\n";
// put pointers to the objects in the vector
attvec.push_back(&q);
attvec.push_back(&w);
attvec.push_back(&e);
attvec.push_back(&r);
attvec.push_back(&t);
attvec.push_back(&y);
attvec.push_back(&u);
// TEST ALL Attribute CLASS INSTANCES AS EXTRACTED FROM A vector
std::cout << "--\n";
for (AttributeBase const* baseObject : attvec) {
// try to dynamic_cast to the types for which you have special handling
// if( <init> ; <condition> ) { ...
if(auto pChild = dynamic_cast<Attribute<String> const*>(baseObject); pChild)
{
std::cout << "T (String)\n";
const String sKey = pChild->getKey();
std::cout << "Key: " << sKey << "\n";
const String sValue = pChild->getValue();
std::cout << "Value: " << sValue << "\n";
// or let the user defined streaming operator for the type do the work:
std::cout << *pChild << "\n\n";
}
else if(auto pChild = dynamic_cast<Attribute<int> const*>(baseObject); pChild)
{
std::cout << "T (int)\n";
const String sKey = pChild->getKey();
std::cout << "Key: " << sKey << "\n";
const int iValue = pChild->getValue();
std::cout << "Value: " << iValue << "\n";
// or let the user defined streaming operator for the type do the work:
std::cout << *pChild << "\n\n";
} else {
std::cout << "T (generic)\n";
const String sKey = baseObject->getKey();
std::cout << "Key: " << sKey << "\n";
/* the getValue() method does not exist in the base class
auto genValue = baseObject->getValue();
cout << "Value: " << genValue << "\n";
*/
// or let the user defined streaming operator for the type do the work:
std::cout << *baseObject << "\n";
}
}
}
I removed the dependency to Attributes.cpp in the makefile so you can remove that file. I also added some things that can come in handy when chasing bugs and made a generic rule for mapping <file>.cpp to obj/<file>.o. I use gmake so it may contain gmake specific things that makes it fail on your side. Just disregard it in that case. Some of the options may still be useful.
Makefile
CC=c++
MINIMAL_WARNINGS=-Wall -Wextra -pedantic
BONUS_WARNINGS=-Werror -Wshadow -Weffc++ -Wconversion -Wsign-conversion -Woverloaded-virtual \
-Wold-style-cast -Wwrite-strings -Wcast-qual -Wnoexcept -Wnoexcept-type \
-Wpessimizing-move -Wredundant-move -Wstrict-null-sentinel -Wunreachable-code \
-Wnull-dereference -Wsequence-point -pedantic-errors
# scan-build — Clang static analyzer
STATIC_ANALYSIS = scan-build -v --force-analyze-debug-code
# SANITIZER options using libasan.
# libasan - good for catching and displaying misc errors in runtime instead of just resulting
# in a "Segmentation fault (core dumped)".
SANITIZER=-fsanitize=undefined -fsanitize=address
# turn on the bonus warnings if you'd like to fix misc things that are usually good to fix.
#WARNINGS=$(MINIMAL_WARNINGS) $(BONUS_WARNINGS)
WARNINGS=$(MINIMAL_WARNINGS)
FLAGS=-g3 -std=c++17 $(WARNINGS)
# collect all your .cpp files - remember to remove Attribute.cpp
SRC=$(wildcard *.cpp)
# Create a list of object files needed before linking.
# For each "%.cpp" file in SRC, "obj/%.o" will be put in OBJS.
OBJS=$(patsubst %.cpp,obj/%.o,$(SRC))
TARGETS=harness
All: $(TARGETS)
harness: $(OBJS)
## turn on SANITIZER on if you have libasan installed (linking will fail if you dont)
##$(CC) $(FLAGS) $(SANITIZER) -o harness $(OBJS)
$(CC) $(FLAGS) -o harness $(OBJS)
# A generic object file rule. It requires a .cpp file and that the obj directory exists.
obj/%.o : %.cpp obj Attribute.h
## turn on STATIC_ANALYSIS if you have scan-build installed
##$(STATIC_ANALYSIS) $(CC) $(FLAGS) -c -o $# $<
$(CC) $(FLAGS) -c -o $# $<
# The object directory target
obj:
mkdir -p obj
clean:
rm -rf obj $(TARGETS)

How to catch the address of the functor generated for a lamda expression?

you know that the compiler transforms a lambda expression into some kind of functor:
the captured variables become data members of this functor. Variables captured by value are copied into data members of the functor. These data members have the same constness as the captured variables et cetera...
Now I wonder if it's possible to catch the address of this hidden object generated from the compiler behind the scenes
I give you a simple snippet of (WRONG) code just to show my intentions:
#include <iostream>
using namespace std;
class MetaData
{
public:
void printAddress()
{
cout << "\n printAddress:Instance of MetaData at &" << this;
}
};
int main()
{
MetaData md1;
cout << "\n &md1 = " << &md1 << "\n";
md1.printAddress();
cout << "\n\n--------------------\n\n";
int i = 5;
auto x = [i]() mutable {
//cout << "\n The address of the functor is &" << this; // ERROR ! ! !
cout << "\n Hello from Lambda ";
cout << "\n &i = " << &i << " ++i ==> " << ++i << endl; };
x(); // executing lambda
auto y = x; // y is constructed with copy ctor
y();
}
Link to Coliru
I'd like hidden functor to behave like MetaDatas.
Can someone clear my mind?
Thanks for your time.
Syntax would be:
auto x = [&](){ std::cout << &x; }; // but it is illegal too:
// variable 'x' declared with deduced type 'auto' cannot appear in its own initializer
Possible work-around is usage of Y-combinator, something like:
auto x = [i](auto& self) mutable {
cout << "\n The address of the functor is &" << &self;
cout << "\n Hello from Lambda ";
cout << "\n &i = " << &i << " ++i ==> " << ++i << endl; };
x(x); // executing lambda
Demo

int function parameter not working properly

I'm trying to make something in C++ and I have a problem. I have this code:
#include <iostream>
#include <string>
//---MAIN---
using namespace std;
int af1 = 1;
int af2 = 1;
void lettersort(int cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
}
int main()
{
lettersort(af2);
return 0;
}
So is there any way so that cnt1++ affects af2 too, to make it bigger ? I don't want to use af2++ directly because I want to sometimes use af1.
At the moment you are just passing af2 to cnt1 by value, so any changes to cnt1 are strictly local to the function lettersort. In order to get the behaviour you want you need to pass your cnt1 parameter by reference. Change:
void lettersort(int cnt1)
to:
void lettersort(int &cnt1)
You are passing the argument by value. I.e., you are copying the value of af1 to a local variable in lettersort. This integer is then incremented, and disposed of when the function ends, without affecting the original af1. If you want the function to be able to affect af1, you should pass the argument by reference:
void lettersort(int& cnt1) { // Note the "&"
if i understood your question:
there are 2 ways you can do that.
make lettersort function return the new value, and put it in af2
int lettersort(int cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
return cnt1;
}
int main()
{
af2 = lettersort(af2);
return 0;
}
pass the value by reference. you can read about it here, but generally its about passing a pointer to that value. meaning whatever you do on the argument you are passing, will happen on the original var.
example:
void foo(int &y) // y is now a reference
{
using namespace std;
cout << "y = " << y << endl;
y = 6;
cout << "y = " << y << endl;
} // y is destroyed here
int main()
{
int x = 5;
cout << "x = " << x << endl;
foo(x);
cout << "x = " << x << endl;
return 0;
}
here you have to just modified the argument pass to lettersort
function as passed by reference.
for example if you declare and initialize any variable like:
int a=10; int &b = a;
now a and b refer to the same value.if you change a then the changes
also reflect in b also.
so,
cout << a; cout << b;
both statement produce the same result across the program. so using
this concept i modified the function argument and made it as by
reference.
your correct code is :
#include <iostream>
#include <string>
using namespace std;
int af1 = 1;
int af2 = 1;
void lettersort(int &cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
}
int main()
{
lettersort(af2);
return 0;
}

Is there any way to access a local variable in outer scope in C++?

Just out of curiosity: if I have nested scopes, like in this sample C++ code
using namespace std;
int v = 1; // global
int main (void)
{
int v = 2; // local
{
int v = 3; // within subscope
cout << "subscope: " << v << endl;
// cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
}
cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
}
Is there any way to access the variable v with the value 2 from the "intermediate" scope (neither global nor local)?
You can declare a new reference as an alias like so
int main (void)
{
int v = 2; // local
int &vlocal = v;
{
int v = 3; // within subscope
cout << "local: " << vlocal << endl;
}
}
But I would avoid this practice this altogether. I have spent hours debugging such a construct because a variable was displayed in debugger as changed because of scope and I couldn't figure out how it got changed.
The answer is No You cannot.
A variable in local scope shadows the variable in global scope and the language provides a way for accessing the global variable by using qualified names of the global like you did. But C++ as an language does not provide anyway to access the intermediate scoped variable.
Considering it would have to be allowed it would require a lot of complex handling, Imagine of the situation with n number of scopes(could very well be infinite) and handling of those.
You are better off renaming your intermediate variables and using those that would be more logical and easy to maintain.
There are two types of scope resolution operators in C++ - unary scope and a class scope. There is no function scope or "any particular parent scope" resolution operators. That makes it impossible to solve your problem, as it is, in general because you cannot refer to anonymous scopes. However, you can either create an alias, rename variables, or make this a part of the class, which of course implies a code change. This is the closest I can get you without renaming in this particular case:
#include <iostream>
using namespace std;
int v = 1; // global
class Program
{
static int v; // local
public:
static int main ()
{
int v = 3; // within subscope
cout << "subscope: " << v << endl;
cout << "local: " << Program::v << endl;
cout << "global: " << ::v << endl;
}
};
int Program::v = 2;
int main ()
{
return Program::main ();
}
There are other ways, like making sure that variables are not optimized out and are on stack, then you can work with stack directly to get the value of the variable you want, but let's not go that way.
Hope it helps!
You could fake it like this:
#include <iostream>
using namespace std;
int v = 1;
int main()
{
int v = 2;
{
int &rv = v; // create a reference
int v = 3; // then shadow it
cout << "subscope: " << v << endl;
cout << "local: " << rv << endl;
cout << "global: " << ::v << endl;
}
cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
return 0;
}
Interestingly this compiles on cygwin g++ but segfaults if you try to run it:
#include <iostream>
using namespace std;
int v = 1;
int main()
{
int v = 2;
{
int &v = v;
cout << "subscope: " << v << endl;
// cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
}
cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
return 0;
}