Strange output, not as expected - c++

sorry for asking you a stupid question, but I just can't figure out why I keep on getting this output.
So here is my code:
#include <cstdio>
#include <iostream>
using namespace std;
unsigned n = 4242;
int getRemainderOf(int m, int n, int& quotient);
static int l = 0;
int main()
{
int quotient; // the value of which should be changed after calling the func.
for(int i=-1; i<=1; ++i)
{
for(int j=-1; j<=1; ++j)
{
if( i && j )
{
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;
cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;
}
}
}
return 0;
}
int getRemainderOf(int m, int n, int& quotient)
{
++l;
cout << l <<endl;
quotient = m / n;
cout << " quotient " << quotient <<endl;
return m % n;
}
so what I expected to see in the first line of my output was the remainder and then the quotient that I get after calling the function getRemainderOf(). But instead when I cout the value of quotient like that I see that the value of quotient is a garbage value. So the value of the variable is not changed even though I've passed it to the function by using reference.
The funny thing is that if I cout the remainder (got by calling the function) and the quotient separately I will get it right.
I see that the problem might be in calling the function as a argument of the operator << function but I don't get it why the value of the quotient isn't changed since I call the function before I output it. This operator's associativity is left-to-right so what's wrong?
So could you please tell me what is the reason of this output.

What you've just found is a classic example of one of the quirks of C++. Your program can actually be decomposed into this simple example:
int i = 10;
f(i, ++i);
The compiler has the choice of function argument evaluation from left-to-right, but this is not guaranteed. Here's some standard text:
5.2/4 Postfix Epressions [expr.post]
When a function is called, each parameter shall be initialized with its corresponding argument. [Note: Such initializations are indeterminatly sequenced with respect to each other (1.9) - end note]
Because they are indeterminatly sequenced, the compiler has the freedom of evaluating ++i before the first argument and initializing it with the corresponding function parameter, and then evaluating i and initializing it with its respective parameter next.
The reason function call argument evaluation ambiguity is applicable here is because operator<<() is a function but it's just being called with the operator syntax. For example, this is what your code looks like if we use the operator-id syntax:
std::operator<<(std::operator<<(std::operator<<(std::cout, "(").operator<<(i*3), ",").operator<<(j*7), ")").operator<<(getRemainderOf(i*3, 7*j, quotient)).operator<<(quotient);
These are just chains of function calls with arguments and they obey the same rule as the one above.
The solution is to sequence the act of modifying the object and using it in the operator<<() call. You already achieved this with partitioning the operator<<() call into two statements with the semicolon ;, so the function is guaranteed to be called before quotient is printed.

The order of evaluation of function arguments is unspecified.
In these statements
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;
cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;
there are called overloaded operators << that are in fact functions. You have to split each statement in two statements. For example
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) ;
cout << " " << quotient <<endl;

Related

print multiple numbers in ascending order in C++

So I'm working on this project where I have to gather 2 integers from a user 3 times (loop), and each time I have to print the two integers in ascending order. The restriction is that you can only have two cout statements within your loop (one is asking for their input and the second is outputting the ascending order).
My only issue with that is, when I think about ascending order, I would do it like (which has two count statements):
if (m<n) {
cout << m << n << endl;
if (m>n){
cout << n << m << endl;
So far, this is what I have:
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z;
for (n=0;n<3;n++){
cout << "Give me two numbers: ";
cin >> m;
cin >> z;
//if (m>z);
//cout << m << z << "sorted is: " << m << z << endl;
// This is where I'm getting stuck because I need two count statements to organize in ascending order as shown above
}
}
So have you considered to change which variable holds the lower number? e.g.
if(m > n){
int temp = n;
n = m;
m = temp;
}
Then you can just use one print
cout << m << " " << n << endl;
This is where I'm getting stuck because I need two count[sic]
statements to organize in ascending order as shown above
You have marked this post as C++:
Additional options to consider:
use algorithm lib:
#include <algorithm>
std::cout << std::min(m,n) << " " << std::max(m,n) << std::endl;
or use conditional / ternary operator in your cout:
std::cout << ((m<n) ? m : n) << " " << ((n<m) ? m : n) << std::endl;
References are sometimes fun ... but perhaps this challenge is too trivial.
// guess m < n
int& first = m;
int& second = n;
if(!(m<n)) { first = n; second = m; }
std::cout << first << " " << second << std::endl;
Pointers can do the same:
// guess m < n
int& first = &m;
int& second = &n;
if(!(m<n)) { first = &n; second = &m; }
std::cout << *first << " " << *second << std::endl;
or you can use
lambda expressions, or
c++ functions, or
c++ class methods
But I think each of these would be directly comparable to either of the first alternatives.

The number of elements in an array using pointers in C++

So while studying for my exams I was trying to do a practice problem for pointers.
In the following code I'm trying to display the number of elements before the first occurrence of 0.
There is only one part that i didn't understand please see the 6th last line.
#include <iostream>
using namespace std;
int main()
{
int A[10];
for (int i = 0; i < 10; i++){
cout << "Please enter number " << i + 1 << " in the array: ";
cin >> A[i];
}
int *Aptr = A;
while(*Aptr !=0){
cout << *Aptr << "";
Aptr++;
}
cout << "\nThere are " << (Aptr - A) //Here is what i don't understand.
<< " numbers before the first occurrence of 0." << endl;
system("pause");
return 0;
}
So why exactly is (Aptr - A) giving me the number of elements instead of a memory location, and why is this even doable since Aptr is a pointer and A is an array?
Can someone explain to me in detail?
When used in an expression, like Aptr - A, the name of an array A will be implicitly converted to a pointer (equal to &A[0]).
Then the compiler is faced with subtracting two pointers of the same type (both of type int * in your case). That is specified as giving a value of type std::ptrdiff_t, which is, in turn "a signed integral type able to represent the result of subtracting two pointers".
Pointer arithmetic, when subtracting two pointers of type int (i.e. two int *s) gives the number of ints between the two pointers (assuming they are in the same object, which is true in this case, since Aptr points at an element of the array A).
Practically, if Aptr is equal to &A[i], the subtraction Aptr - &A[0] gives a std::ptrdiff_t equal to i.
Note: there is another problem in your code, as since the first (for) loop reads 10 values, while the second while loop keeps incrementing Aptr until it points at an int with value 0. If the user enters any zero values, the second loop will stop when it finds the first (even if the user enters non-zero elements after that). If the user enters no values equal to 0, then the while loop has undefined behaviour, since Aptr will keep walking through memory past the end of A until it happens to find memory that compares (as an int) equal to 0.
First of all, name of array A is associated to address of (pointer at) the first item in the array.
So why exactly is (Aptr - A) giving me the number of elements?
Because according to rules address arithmetic subtraction operation (also +, and similar) is performed based on the data type.
I mean, that compiler operating with int* makes ++, --, addition, subtraction an integer, etc. adds addresses needed for shifting to next/previous item.
If you really want to see how many bytes are located between addresses, just convert addresses to int before making subtraction:
cout << endl << "Address difference is " << int(Aptr) - int(A) << endl;
You can try that with different data types as follows:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int A[5];
short B[5];
unsigned char C[5];
cout << "Array (data type) | Syze of array | Size of item | Item distanse | Bytes distance" << endl;
cout << "A (int) :" << setw(10)
<< sizeof(A) << setw(15)
<< sizeof(A[0]) << setw(15)
<< &A[4] - A << setw(15)
<< int(&A[4]) - int(A) << endl;
cout << "B (short) :" << setw(10)
<< sizeof(B) << setw(15)
<< sizeof(B[0]) << setw(15)
<< &B[4] - B << setw(15)
<< int(&B[4]) - int(B) << endl;
cout << "C (un.char) :" << setw(10)
<< sizeof(C) << setw(15)
<< sizeof(C[0]) << setw(15)
<< &C[4] - C << setw(15)
<< int(&C[4]) - int(C) << endl;
system("pause");
return 0;
}
UPDATE
To be better prepared for your exam, consider the following example with pointers:
#include <iostream>
using namespace std;
int main()
{
int A[5] = {0}; // all items now are 0
int * P = A + 2; // the same as P = &A[2];
*P = 33; // writing to item A[2];
cout << A[2] << endl; // just to check in usual way
cout << *(A + 2) << endl; // using A as a pointer
cout << *(2 + A) << endl; // almost the same to previous
cout << 2[A] << endl; // quite strange, but it works
cout << 0[P] << endl; // and this is the same
return 0;
}
You must understand that 0[P] means for compiler *(0 + P), as well as 2[A] means - *(2 + A), but you should not write in your program in such style (exceptions are only cases when you want to confuse a reader).
And one more important thing - difference between array and pointer - are shown in the following example:
int A[] = {1, 2, 3, 4, 5};
int *P = A;
cout << "A = " << A << endl;
cout << "P = " << P << endl;
cout << "size of A = " << sizeof(A) << endl;
cout << "size of P = " << sizeof(P) << endl;
even if the addresses (vaules A and P) are equal, compiler works with array (A) in a different way than with pointer: sizeof(A) means memory allocated for whole array (5 items of sizeof(int) each), but sizeof(P) means memory allocated for data type int * (pointer to int). So, sizeof(P) depends only on compiler and OS platform (e.g. pointer can be 32-bit or 64-bit), but sizeof(A) depends on size of item (int may be not 32 bits) and NUMBER OF ITEMS in the array.
And you can "go to the next item" with pointer:
P++;
cout << *P << endl;
but you are not able to do:
A++;
because A is not variable of pointer type (it is just similar in sense of "address of the first item"), and compiler will say you something like:
error : '++' needs l-value

Modular Arithmetic addition and subtraction using Crypto++

I am very new to this, but I am trying to add two Integers in modular format using Crypto++ Library.
My program is very simple,
AutoSeededRandomPool prng;
Integer r0, m;
m = Integer( prng, 64);
r0 = Integer( prng, 64);
cout << "m: " << std::hex << m << endl;
cout << "r0:" << std::hex << r0 << endl;
Integer n1(r0 + m);
But this simply didn't work. It complied fine, but it crashed when I was trying to run it.
Could anyone give a sample code for addition/subtraction using Crypto++ please
Modular Arithmetic (addition/subtraction) using Crypto++
We have closed some of the missing documentation gaps based on this question, so I won't address the sample code. The improved docs are available at Integer Class Reference and Integer on the Crypto++ wiki.
However, there may be a bug or (at least) unexpected results from using the ModularArithmetic class. The class describes itself as "Ring of congruence classes modulo n". Mathematically, a Ring is a group with closure and two well defined operations.
The disconnect is, which two operations are the ones included with ModularArithmetic<Integer>. Based on some sample code, it looks like its Multiply and Exponentiate, which is mostly expected (though it could have been Add and Multiply).
I don't think the mathematical definition of Ring gives ModularArithmetic a license to produce unexpected results. However, ModularArithmetic is kind of unique, and it may be accumulating intermediate results that one must then reduce using Multiply and Exponentiate. (It does accumulate results to speed up operations).
The open question for me is, what do we do... I'm trying to solicit some feedback at the moment on the issue.
Here's the test program:
int main(int argc, char* argv[])
{
Integer m("4294967295"), n("0x1000000000000000000000000000000"), j;
j = 1999;
ModularArithmetic ma(j);
cout << "n+m mod j: " << ma.Add(n, m) << endl;
cout << " cross-check: " << (n+m) % j << endl;
cout << "n-m mod j: " << ma.Subtract(n, m) << endl;
cout << " cross-check: " << (n-m) % j << endl;
cout << "n*m mod j: " << ma.Multiply(n, m) << endl;
cout << " cross-check: " << (n*m) % j << endl;
cout << "n/m mod j: " << ma.Divide(n, m) << endl;
cout << " cross-check: " << (n/m) % j << endl;
cout << "n%m mod j: " << ma.Reduce(n, m) << endl;
cout << " cross-check: " << (n%m) % j << endl;
cout << "n^m mod j: " << ma.Exponentiate(n, m) << endl;
cout << " cross-check: " << a_exp_b_mod_c(n,m,j) << endl;
return 0;
}
Here are the results:
$ ./test.exe
n+m mod j: 1329227995784915872903807064575309872.
cross-check: 1755.
n-m mod j: 1329227995784915872903807055985377281.
cross-check: 50.
n*m mod j: 266.
cross-check: 266.
n/m mod j: 599.
cross-check: 1997.
n%m mod j: 1329227995784915872903807055985377281.
cross-check: 1608.
n^m mod j: 1326.
cross-check: 1326.
EDIT 1
The disconnect is, which two operations are the ones included with ModularArithmetic<Integer>...
So I had a chance to go though the source code and add more missing documentation. Of particular interest is AbstractRing< T > Class Template Reference, which ModularArithmetic inherits from. It confirms that multiply and exponentiation are the operations (and it gives rise to helpers, like Square).
What I am not clear about is why ModularArithmetic is providing Add, Subtract and friends but arriving at unexpected results. It could well be that its effectively accumulating the results and waiting to be reduced with a Multiply or Exponentiate, but I don't see any comments in the source code.
EDIT 2
The reason ModularArithmetic appears to produce incorrect results for Add, Subtract and friends is the class is meant to be fast for specific problems, and it does not perform a full reduction using the Euclidean extended algorithm. Rather, it performs at most one subtraction. That means the accumulated value n to be reduced by the modulus p must be in the range [0, 2p).

Random Number Order in C++ using <random>

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.

Pre / Post Increment Explanation

Please be easy on me and don't shoot me as I'm still newbie.
I'm totally confused and can't for life figure out why when I run this code:
int y = 9;
cout << "++y = " << ++y << "\n--y = " << --y << "\ny++ = " << y++ << "\ny-- = " << y-- << "\n";
cout << "y = " << y << "\n";
I get the following results:
y = 9
++y = 9
--y = 9
y++ = 8
y-- = 9
y = 9
instead of these results:
y = 9
++y = 10
--y = 9
y++ = 9
y-- = 10
y = 9
That I get from this code:
int y = 9;
cout << "y = " << y << "\n";
cout << "++y = " << ++y << "\n";
cout << "--y = " << --y << "\n";
cout << "y++ = " << y++ << "\n";
cout << "y-- = " << y-- << "\n";
cout << "y = " << y << "\n";
Can anyone explain -in simple words as possible- what happens in the first code so that it prints the result that way?
A simple rule is that you are not expected to increment the same location more than once in any given statement. So you should not code cout << y++ << ++y << endl; which contain two increments of y (assuming an int y; declaration).
For details, read about sequence points and undefined behavior in the C++ standard.
There are lot of related questions. Look into them for more!
When according to the rules operation * is to be counted before +, and ++ before *, it will be so.
a*b++ + c // first b++ (returns **old** b), than a*b, than ...+c
But when you have a++ * a--, nobody can tell, what of the two operands, a++ or a-- will be evaluated the first. According to ANSII standard, even if you use the same translator, the result is every time unpredictable.
cite from the C++ ANSII standard:
Except where noted, the order of evaluation of operands of individual
operators and subexpressions of individual expressions, and the order
in which side effects take place, is unspecified. Between the previ-
ous and next sequence point a scalar object shall have its stored
value modified at most once by the evaluation of an expression. Fur-
thermore, the prior value shall be accessed only to determine the
value to be stored. The requirements of this paragraph shall be met
for each allowable ordering of the subexpressions of a full expres-
sion; otherwise the behavior is undefined. [Example:
i = v[i++]; // the behavior is undefined
i = 7, i++, i++; // `i' becomes 9
i = ++i + 1; // the behavior is undefined
i = i + 1; // the value of 'i' is incremented
Sequence points:
at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression);
at the ||, &&, ?:, and comma operators;
and at a function call (after the evaluation of all the arguments, and
just before the actual call).
So, || is a sequence point, but << is not.
Mulitiline version of first code should be:
y = 9;
cout << "y-- = " << y-- << "\n";
cout << "y++ = " << y++ << "\n"
cout << "--y = " << --y << "\n"
cout << "++y = " << ++y << "\n"
cout << "y = " << y << "\n";