AFAIK it is illegal to take the address of an rvalue because the address-of operator & takes an lvalue and returns the address of the object's called on address.
Here is an example I've tried to understand but find it a bit confusing:
#include <deque>
#include <iostream>
int main() {
using std::cout;
using std::endl;
std::deque<int> di{ 1, 1, 2, 3, 5, 8, 13 };
std::deque<int>::iterator it = di.end() - 1;
cout << *it << endl;
cout << &it-- << endl; // is it UB?
cout << *it << endl;
cout << &it-- << endl;
cout << *it << endl;
cout << &it-- << endl;
cout << *it << endl << endl;
cout << &--it << endl; // ok
cout << *it << endl; // ok
cout << &--it << endl; // ok
cout << *it << endl; // ok
std::cout << std::endl << "done!" << std::endl;
}
In the lines where I've used the pre-decrement operator it is OK because this operator and & have the same precedence level and are evaluated from right-to-left (RL) thus -- evaluates first and it returns an lvalue (takes also lvalue). then & is evaluated so & on an lvalue is OK.
The problem above in the post-decrement operator which takes an lvalue and returns an rvalue and has higher precedence over &. So in these expressions I am calling & on rvalue which is normally not allowed. But why the code compile and gives different results (addresses)??
When compiled on Wandbox with flag -pedantic it doesn't compile:
prog.cc:25:17: error: taking address of rvalue [-fpermissive]
25 | cout << &offEnd-- << endl; // -- has higher precedence than & thus this expression decrements offEnd and returns a copy of original of offEnd then print the address of this original object (before decrementing it)
Also on MSVC++14 with /Wall.
So is it undefined behavior in my code?
so why C++ allowed calling address of operator & on rvalue while the standard disallows it?
Finally I want to know where theses different addresses come from in such expression: std::cout << &it-- << std::endl;? But the values of de-referencing are correct!
So my professor told my class to run this program, it supposedly shows what's going on in computer memory. When I ran it, my output file had the same numbers as my professor's output file for the first like 4 lines and then totally different numbers from then on. But this certainly doesn't seem like it's pulling random numbers, because a lot of the output is 0s and a lot of it are large numbers of similar lengths. Can anyone explain this?
#include <iostream>
#include <fstream> // for files
#include <cstdlib> // for exit
#include <climits> // for INT_MAX etc.
int main( )
{
using namespace std;
ofstream outfile;
outfile.open("Whats_in_computer_memory.txt");
cout << "In this program, we declare a small array and then use array syntax " << endl
<< "to see what is in the computer's memory. " << endl
<< " " << endl
<< " " << endl
<< " " << endl
<< " " << endl
<< " " << endl;
int a[1];
int histogram[214749];
for (int i = 0; i < 214749; i++ )
{
histogram[i] = 0;
}
cout << "&a[0] = " << &a[0] << endl
<< "&histogram[0] = " << &histogram[0]<< endl
<< " " << endl;
cout << INT_MAX << endl;
for (int i = 0; i < 1000; i++ )
{
outfile << a[i] << endl;
//cout << INT_MAX/1000000 +a[i]/1000000 << endl;
//histogram[ a[i]/1000000 ]++;
}
for (int i = 0; i < 2 ; i++ )
{
cout << histogram[ i ] << endl;
}
char dummy;
cin >> dummy;
return 0;
}
a has one element. That means
for (int i = 0; i < 1000; i++ )
{
outfile << a[i] << endl;
//cout << INT_MAX/1000000 +a[i]/1000000 << endl;
//histogram[ a[i]/1000000 ]++;
}
is undefined behavior as soon as i >= 1. Once you have undefined behavior anything can happen so we can no longer reason out what is going on.
Your professor is trying to demonstrate that the area of memory around your program contains "stuff" - specifically that the memory around your program isn't zero'd or set to any other default value.
Presumably, this is part of a further point that accessing memory out-of-bounds doesn't guarantee that you'll have any particular value, and as such need to initialise your variables accordingly.
However; the problem is that we consider "accessing out-of-bounds of an array" to be undefined behaviour. Undefined behaviour in the C++ standard means "the compiler can handle this situation in whatever way it considers appropriate". Most compilers will serve you values from nearby memory locations (this being simple to do), but they're not required to do so.
Likewise, some compilers can aggressively optimise-out undefined behaviour (like concluding that i can never be greater than 1 when used to index into a, and adjusting the loop appropriately): compilers are free to assume (for optimisation purposes) that undefined behaviour is never invoked by the programmer. See this page from the LLVM project for more details on undefined behaviour (noting that under "Dereferences of Wild Pointers and Out of Bounds Array Accesses", both the Clang team and g++ have made the same decision with regards to handling out-of-bounds errors: they access nearby memory locations; because it's the simplest thing to do in that case).
I have the following code, that I wrote to test a part of a larger program :
#include <fstream>
#include <random>
#include <iostream>
using namespace std ;
int main()
{
mt19937_64 Generator(12187) ;
mt19937_64 Generator2(12187) ;
uniform_int_distribution<int> D1(1,6) ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << " " << D1(Generator) << endl ;
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
ofstream g1("g1.dat") ;
g1 << Generator ;
g1.close() ;
ofstream g2("g2.dat") ;
g2 << Generator2 ;
g2.close() ;
}
The two generators are seeded with the same value, and therefore I expected the second row in the output to be identical to the first one. Instead, the output is
1 1 3
1 3 1
The state of the two generators as printed in the *.dat files is the same. I was wondering if there might be some hidden multi-threading in the random number generation causing the order mismatch.
I compiled with g++ version 5.3.0, on Linux, with the flag -std=c++11.
Thanks in advance for your help.
x << y is syntactic sugar for a function call to operator<<(x, y).
You will remember that the c++ standard places no restriction on the order of evaluation of the arguments of a function call.
So the compiler is free to emit code that computes x first or y first.
From the standard: §5 note 2:
Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause
9) or enumeration type (7.2). Uses of overloaded operators are transformed into function calls as described
in 13.5. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of
operand type, value category, and evaluation order are replaced by the rules for function call.
That's because the order of evaluation of this line
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
is not what you think.
You can test it with this:
int f() {
static int i = 0;
return i++;
}
int main() {
cout << f() << " " << f() << " " << f() << endl ;
return 0;
}
Output: 2 1 0
The order is not specified by the C++ standard, so the order could be different on other compilers, please see Richard Hodges' answer.
A slight change to the program reveals what happens:
#include <fstream>
#include <random>
#include <iostream>
using namespace std ;
int main()
{
mt19937_64 Generator(12187) ;
mt19937_64 Generator2(12187) ;
uniform_int_distribution<int> D1(1,100) ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << endl ;
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
}
Output:
4 48 12
12 48 4
So your Generators produce equal results - but the order the arguments of your cout-line are calculated in different order.
Try it online:
http://ideone.com/rsoqDe
These lines
cout << D1(Generator) << " " ;
cout << D1(Generator) << " "
<< D1(Generator) << endl ;
cout << D1(Generator2) << " "
<< D1(Generator2) << " "
<< D1(Generator2) << endl ;
because D1() returns an int, for which ostream::operator<<() has an overload, are effectively calling (excluding endl)
cout.operator<<(D1(Generator));
cout.operator<<(D1(Generator))
.operator<<(D1(Generator));
cout.operator<<(D1(Generator2))
.operator<<(D1(Generator2))
.operator<<(D1(Generator2));
Now, the standard has this to say,
§ 5.2.2 [4]
When a function is called, each parameter shall
be initialized with its corresponding argument.
[ Note: Such initializations are indeterminately sequenced with respect to each other — end note ]
If the function is a non-static
member function, the this parameter of the function shall be
initialized with a pointer to the object of the call
So let's break down the preceding expression
cout.operator<<(a()) // #1
.operator<<(b()) // #2
.operator<<(c()); // #3
To illustrate the construction of the this pointer, these are conceptually equivalent to (omitting ostream:: for brevity):
operator<<( // #1
&operator<<( // #2
&operator<<( // #3
&cout,
a()
), // end #3
b()
), // end #2
c()
); // end #1
Now let's look at the top-level call. Which do we evaluate first, #2, or c()? Since, as emphasized in the quote, the order is indeterminate, then we don't know—and this is true recursively: even if we evaluated #2, we would still face the question of whether to evaluate its internal #3 or b().
So that hopefully explains what's going on here more clearly.
I was trying to find the memory address of an array elements but the output is turning out to be in Hexadecimal. I would appreciate if u could tell me how to convert it to a Decimal output.
Here is the Code,
#include<iostream>
using namespace std;
int main()
{
int a[4];
cout << "Address of a[0] = " << &a << endl;
cout << "Address of a[1] = " << &a[1] << endl;
cout << "Address of a[2] = " << &a[2] << endl;
cout << "Address of a[3] = " << &a[3] << endl;
cin.get();
return 0;
}
In C++11 you can cast to uintptr_t, like
cout << "Address of a[0] = " << static_cast<uintptr_t>(&a) << endl;
The type uintptr_t is specifically designed to represent any possible pointer, so the solution is portable.
I am not aware of a portable solution in C++98/03, although a cast to size_t often (but not always) works. Related: Converting a pointer into an integer.
EDIT
Looking at http://en.cppreference.com/w/cpp/types/integer and also at the C++ standard 18.4.1 Header <cstdint> synopsis [cstdint.syn], it looks like uintptr_t is optional. I have no idea whether there is an implementation that does not define it, and why would one chose to not define it. Any comments are welcome.
I noticed if I print out a long string(char*) using cout it seems to print 1 character at a time to the screen in Windows 7, Vista, and Linux(using putty) using Visual C++ 2008 on Windows and G++ on Linux. Printf is so much faster I actually switched from cout to printf for most printing in a project of mine. This is confusing me because this question makes it seem like I'm the only one having this issue.
I even wrote a cout replacement that looks like it beats the pants off of cout on my comp -
class rcout
{
public:
char buff[4096];
unsigned int size;
unsigned int length;
rcout()
{
size = 4096;
length = 0;
buff[0] = '\0';
}
~rcout()
{
printf("%s", buff);
}
rcout &operator<<(char *b)
{
strncpy(buff+length, b, size-length);
unsigned int i = strlen(b);
if(i+length >= size)
{
buff[size-1] = '\0';
printf("%s", buff);
b += (size-length) -1;
length = 0;
return (*this) << b;
}
else
length += i;
return (*this);
}
rcout &operator<<(int i)
{
char b[32];
_itoa_s(i, b, 10);
return (*this)<<b;
}
rcout &operator<<(float f)
{
char b[32];
sprintf_s(b, 32, "%f", f);
return (*this)<<b;
}
};
int main()
{
char buff[65536];
memset(buff, 0, 65536);
for(int i=0;i<3000;i++)
buff[i] = rand()%26 + 'A';
rcout() << buff << buff <<"\n---"<< 121 <<"---" << 1.21f <<"---\n";
Sleep(1000);
cout << "\n\nOk, now cout....\n\n";
cout << buff << buff <<"\n---"<< 121 <<"---" << 1.21f <<"---\n";
Sleep(1000);
cout << "\n\nOk, now me again....\n\n";
rcout() << buff << buff <<"\n---"<< 121 <<"---" << 1.21f <<"---\n";
Sleep(1000);
return 0;
}
Any ideas why cout is printing so slowly for me?
NOTE: This experimental result is valid for MSVC. In some other implementation of library, the result will vary.
printf could be (much) faster than cout. Although printf parses the format string in runtime, it requires much less function calls and actually needs small number of instruction to do a same job, comparing to cout. Here is a summary of my experimentation:
The number of static instruction
In general, cout generates a lot of code than printf. Say that we have the following cout code to print out with some formats.
os << setw(width) << dec << "0x" << hex << addr << ": " << rtnname <<
": " << srccode << "(" << dec << lineno << ")" << endl;
On a VC++ compiler with optimizations, it generates around 188 bytes code. But, when you replace it printf-based code, only 42 bytes are required.
The number of dynamically executed instruction
The number of static instruction just tells the difference of static binary code. What is more important is the actual number of instruction that are dynamically executed in runtime. I also did a simple experimentation:
Test code:
int a = 1999;
char b = 'a';
unsigned int c = 4200000000;
long long int d = 987654321098765;
long long unsigned int e = 1234567890123456789;
float f = 3123.4578f;
double g = 3.141592654;
void Test1()
{
cout
<< "a:" << a << “\n”
<< "a:" << setfill('0') << setw(8) << a << “\n”
<< "b:" << b << “\n”
<< "c:" << c << “\n”
<< "d:" << d << “\n”
<< "e:" << e << “\n”
<< "f:" << setprecision(6) << f << “\n”
<< "g:" << setprecision(10) << g << endl;
}
void Test2()
{
fprintf(stdout,
"a:%d\n"
"a:%08d\n"
"b:%c\n"
"c:%u\n"
"d:%I64d\n"
"e:%I64u\n"
"f:%.2f\n"
"g:%.9lf\n",
a, a, b, c, d, e, f, g);
fflush(stdout);
}
int main()
{
DWORD A, B;
DWORD start = GetTickCount();
for (int i = 0; i < 10000; ++i)
Test1();
A = GetTickCount() - start;
start = GetTickCount();
for (int i = 0; i < 10000; ++i)
Test2();
B = GetTickCount() - start;
cerr << A << endl;
cerr << B << endl;
return 0;
}
Here is the result of Test1 (cout):
# of executed instruction: 423,234,439
# of memory loads/stores: approx. 320,000 and 980,000
Elapsed time: 52 seconds
Then, what about printf? This is the result of Test2:
# of executed instruction: 164,800,800
# of memory loads/stores: approx. 70,000 and 180,000
Elapsed time: 13 seconds
In this machine and compiler, printf was much faster cout. In both number of executed instructions, and # of load/store (indicates # of cache misses) have 3~4 times differences.
I know this is an extreme case. Also, I should note that cout is much easier when you're handling 32/64-bit data and require 32/64-platform independence. There is always trade-off. I'm using cout when checking type is very tricky.
Okay, cout in MSVS just sucks :)
I would suggest you try this same test on a different computer. I don't have a good answer for why this might be happening; all I can say is I have never noticed a speed difference between cout and printf. I also tested your code using gcc 4.3.2 on Linux and there was no difference whatsoever.
That being said, you can't easily replace cout with your own implementation. The fact is, cout is an instance of std::ostream which has a lot of functionality built into it which is necessary for interoperability with other classes that overload the iostream operators.
Edit:
Anyone that says printf is always faster than std::cout is simply wrong. I just ran the test code posted by minjang, with gcc 4.3.2 and the -O2 flag on a 64-bit AMD Athlon X2, and cout was actually faster.
I got the following results:
printf: 00:00:12.024
cout: 00:00:04.144
Is cout always faster than printf? Probably not. Especially not with older implementations. But on newer implementations iostreams are likely to be faster than stdio because instead of parsing a format string at runtime, the compiler knows at compile time what functions it needs to call in order to convert integers/floats/objects to strings.
But more importantly, the speed of printf versus cout depends on the implementation, and so the problem described by the OP is not easily explicable.
Try call ios::sync_with_stdio(false); before using std::cout/cin, unless of course, you mix stdio and iostream in your program, which is a bad thing to do.
Based on my experience in programming competitions, printf IS faster than cout.
I remember many times when my solution didn't make it before the Time limit just because of cin/cout, while printf/scanf did work.
Besides that, it seems normal (at least for me) that cout is slower than printf, because it does more operations.
Try using some endls or flushes as they will flush cout's buffer, in case the OS is caching your program's output for whatever reason. But, as Charles says, there's no good explanation for this behavior, so if that doesn't help then it's likely a problem specific to your machine.
You should try to write all your data to an ostringstream first, and then use cout on the ostringstream's str(). I am on 64-bit Windows 7 and Test1 was already significantly faster than Test2 (your mileage may vary). Using an ostringstream to build a single string first and then using cout on that further decreased Test1's execution time by a factor of about 3 to 4. Be sure to #include <sstream>.
I.e., replace
void Test1()
{
cout
<< "a:" << a << "\n"
<< "a:" << setfill('0') << setw(8) << a << "\n"
<< "b:" << b << "\n"
<< "c:" << c << "\n"
<< "d:" << d << "\n"
<< "e:" << e << "\n"
<< "f:" << setprecision(6) << f << "\n"
<< "g:" << setprecision(10) << g << endl;
}
with:
void Test1()
{
ostringstream oss;
oss
<< "a:" << a << "\n"
<< "a:" << setfill('0') << setw(8) << a << "\n"
<< "b:" << b << "\n"
<< "c:" << c << "\n"
<< "d:" << d << "\n"
<< "e:" << e << "\n"
<< "f:" << setprecision(6) << f << "\n"
<< "g:" << setprecision(10) << g << endl;
cout << oss.str();
}
I suspect ostringstream makes this so much faster as a result of not trying to write to the screen each time you call operator<< on cout. I've also noticed through experience that reducing the number of times you write to the screen (by writing more at once) increases performance (again, your mileage may vary).
E.g.,
void Foo1()
{
for(int i = 0; i < 10000; ++i) {
cout << "Foo1\n";
}
}
void Foo2()
{
std::string s;
for(int i = 0; i < 10000; ++i) {
s += "Foo2\n";
}
cout << s;
}
void Foo3()
{
std::ostringstream oss;
for(int i = 0; i < 10000; ++i) {
oss << "Foo3\n";
}
cout << oss.str();
}
In my case, Foo1 took 1,092ms, Foo2 took 234ms, and Foo3 took 218ms. ostingstreams are your friend. Obviously Foo2 and Foo3 require (trivially) more memory. To compare this against a C-style function, try sprintf into a buffer and then write that buffer using fprintf and you should see still more efficiency over Test2 (though for me this only improved performance of Test2 by about 10% or so; cout and printf are indeed different beasts under the hood).
Compiler: MinGW64 (TDM and its bundled libraries).
Try using ios::sync_with_stdio(false);. Mention it before using std::cin/cout. It doesn't mix stdio or iostream but it synchronizes iostream standard streams with their corresponding standard c streams.
for example - std::cin/wcin of iostream is synchronized with stdin of c stream
Here is hax that should make c++ streams as fast as c printf. I never tested it but I believe it works.
ios_base::sync_with_stdio(0);