how does global variable increment work in c++ - c++

#include <iostream>
int counter = 0;
int f(){
return counter++;
}
int main(){
std::cout << f(); //output = 0
std::cout << f()+f(); // output = 1;
return 0;
}
This might be a silly question but why isn't f() equal to 1 instead of 0 in the first case?
I thought counter++ was the same as counter = counter + 1?

No. counter++ is closer to (counter = counter + 1) - 1

Its because of the difference between postfix and prefix notation. In postfix notation which is what you have currently it saves a copy of the variable and then increments the variable for any calls below the current call however at the current call it will appear to stay the same.
This is why when we have std::cout << f(); //output = 0 it outputs 0 because counter will only increment after this line. If you change f to:
int f() { return ++counter; }
You will see the result you expected.

first, Are you sure f() + f() results in 1. I think it should be 3.
Regarding your main question:
post increment works on a copy of the original value. so your function in f() is acting as:
int f()
{
int temp = counter;
counter = counter + 1;
return temp;
}
or as cleverly noted by #kmkaplan:
int f()
{
return (counter = counter + 1 ) - 1;
}
it is similar to the semantic of:
int f = 0;
cout << f++; // f original value is first displayed.
cout << ++f; // f is incremented then displayed.
In general, I prefer to use ++n over n++ unless the program logic requires the opposite.

Related

How to get arbitrary return values in c++

I am trying to write divisor function, Which gives all divisor of given number. But in that I do not want any array rather I want to return every divisors one by one. Is it possible?
This is code :
auto allDivisor(int num){
for (int i=1; i<=num; i++){
if(num % i == 0){
return i;
}
}
But I got only first iterations result:
Enter integer number : 10 All divisior of 10 : 1
#include <iostream>
void allDivisor(int num, void (*callback)(int)) {
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
callback(i);
}
}
}
int main() {
int num = 10;
std::cout << "All divisors of " << num << ": ";
allDivisor(num, [](int divisor) {
std::cout << divisor << " ";
});
std::cout << std::endl;
return 0;
}
The callback function is passed to the allDivisor function as an argument, and it is called once for each divisor of the input number.
the usual way is to call your function multiple times and each time it will return different divisor until the end is marked by some special return value like 0 ... the iteration can be done either by passing i as function parameter or have it as global or static variable but that would make your function thread unsafe prohibiting to use it in parallel (even in serial overlapped with other division) ... It would look like this:
int allDivisor(int num)
{
static int i=0;
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; return 0; }
}
and usage:
int d,X;
for (X=32;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
for (X=125;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
outputting this:
1
2
4
8
16
32
1
5
25
125
however be sure you always call the allDivisor until it returns 0 otherwise its next usage would be messedup (skipped first divisors until last i state) ... that could be repaired too for example like this (at cost of another static variable):
int allDivisor(int num)
{
static int i=0,n=0;
if (n!=num){ n=num; i=0; }
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; n=0; return 0; }
}

Number of additions in a recursive function without using global variables in c++

I have to implement a counter that counts the number of additions in this recursive function, but i am not allowed to use global variables. Do you know how to do that? For example if the function has to call itself free times then my counter has to be put on three at the end of the function just before the return.
long lindh(unsigned int n) {
long lin = 0;
if (n == 1 || n == 2) {
lin = 1;
} else {
lin = 1 * lindh(n - 1) + 3 * lindh(n - 2);
}
return lin;
}
int main() {
long b = 0;
b = lindh(24);
cout << "lindhauer " << b << endl;
return 0;
}
You can change the function signature to be:
long lindh(unsigned int n, int &count)
Pass it the variable you want the count to end up in, in both the initial call and every recursive one. Increment count in the appropriate places.
You can define an overloaded lindh function that takes two arguments. The overloaded function takes two parameters, while the version called from main is the "base" function that just delegates to the overloaded function.
In addition, since you need to return both a lin value and count, you can return a std::pair<long, int> to denote the lin value and count. This eliminates the need for a global variable,
Here is an example:
#include <utility>
#include <iostream>
long lindh(unsigned int n, int &count)
{
long lin = 0;
if (n == 1 || n == 2) {
lin = 1;
} else {
++count;
lin = 1 * lindh(n - 1, count) + 3 * lindh(n - 2, count);
}
return lin;
}
std::pair<long,int> lindh(unsigned int n)
{
int count = 0;
return {lindh(n, count), count};
}
int main()
{
auto b = lindh(24);
std::cout << "lindhauer = " << b.first << "\ncount = " << b.second << std::endl;
}
Live Example

Value assignment into array c++

I'm trying to create a array of prime numbers done by calculation. As a project to learn coding. Ultimately to build my own math library so this is something I can add onto at a variety of levels as I learn to code c++.
The following is code that works great for printing prime numbers to the screen based on the search range, but my totalPrimes iterator is stuck at 1. So each time it places the last prime found in the PrimeNumbers[1] position.
Any advice would be awesome.
#include <iostream>
#include <array>
std::array<long, 10000000> PrimeNumbers={0};
void isPrime(long x);
int main() {
for (long i = 1; i < 10; i++) {
isPrime(i);
}
for(int h = 0; h < 10; h++) {
std::cout << "\nSecond Prime is : " << PrimeNumbers[h];
}
}
void isPrime(long x) {
int count(0), totalPrimes(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
if (count == 1) {
++totalPrimes;
std::cout << '\n' << x << " is a Prime number";
PrimeNumbers[totalPrimes] = x;
}
}
You're initializing totalPrimes to 0 every time the function runs. You would need to have totalPrimes as a global variable, or better yet (because global variables can become problematic), set it equal to the first available member of PrimeNumbers before you do anything else in that function.
Keep track of a position along with your PrimeNumbers array.
size_t nLastPos=0;
...
for(size_t x = 0; 1000 > x; ++x)
{
if(isPrime(x))
{
PrimeNumbers[nLastPos++] = x;
}
}
for(size_t i = 0; nLastPos > n; ++n)
{/* print out number PrimeNumbers[n] */ }
It looks like you're having some trouble with variable scoping. The reason for your problem (as I noted in the comment) is that totalPrimes is local, so you're creating a new integer variable and setting it to 0 every time the function is called.
However, you've made PrimeNumbers global and are having the isPrime function modify it, which doesn't look like good practice.
All of this can be fixed with a little restructuring to make the code nicer:
#include <iostream>
#include <array>
bool isPrime(long x);
int main() {
std::array<long, 10000000> PrimeNumbers={0};
int totalPrimes = 0;
for (long i = 1; i < 10; i++) {
if (isPrime(i)) {
std::cout << '\n' << i << " is a Prime number";
PrimeNumbers[totalPrimes++] = i;
}
}
for(int h = 0; h < 10; h++) {
std::cout << h << " Prime is : " << PrimeNumbers[h] << std::endl;
}
}
bool isPrime(long x) {
int count(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
return count == 1;
}
Your program can be re-structured little bit to make it easier to follow and debug.
Don't put things in isPrime other than the logic to decide whether a number is prime. Make sure it returns a bool. This will make the function a bit simpler and easier to debug.
Use the return value of isPrime in the calling function to perform other bookkeeping tasks.
The logic you have used to check whether a number is prime is incorrect. That needs to be fixed.
Here's an updated version of your posted code.
#include <iostream>
#include <array>
#include <cmath>
std::array<long, 10000000> PrimeNumbers={0};
bool isPrime(long x);
int main()
{
int totalPrimes = 0;
for (long i = 1; i < 10; i++)
{
if ( isPrime(i) )
{
std::cout << i << " is a Prime number" << std::endl;
PrimeNumbers[totalPrimes] = i;
++totalPrimes;
}
}
}
bool isPrime(long x) {
// 1, 2, and 3 are primes.
if ( x <= 3 )
{
return true;
}
// Even numbers are not primes.
if ( x % 2 == 0 )
{
return false;
}
// Check the rest.
long end = (long)std::sqrt(x);
for (long a = 3; a < end; a += 2) {
if ((x % a) == 0)
{
return false;
}
}
return true;
}
and its output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
9 is a Prime number
Everybody is talking about how your totalPrimes variable is reset each time the function is called, and this is obviously true. You could return the value from the function and increment it from main, you could use global variables having the variable being defined outside of the function so that it's not reset each time inside the function or you could use
A static variable!
Take a look at this simple case. I have a function called up_two which increases the value of by two each time the function is called. The static variable int value has a memory of each time the function up_two() is called which increments value by two each time. If I were to use a just an integer it would always reset the value and have it be zero, which is what I initially defined it to be.
The advantage of using a static variable is that I can count how many times a function has been called, and I can keep my counter specific to a particular function.
#include <iostream>
using namespace std;
void up_two();
int main()
{
for(int i = 0; i < 10; i++)
{
up_two();
}
return 0;
}
void up_two()
{
static int value = 0;
cout << value << endl;
value += 2;
}
This program doesn't solve the particular problem that you want to solve, but if you figure out how the static variable is working, it should make your workflow easier.
The magic line here is this:
static int value = 0;
With it like this my program prints the following:
0
2
4
6
8
10
12
14
16
18
Without the static declaration, you just get 10 lines of zeroes
which is troublesome.
Hope that helps you optimize your program the way you want it to be.

What is the purpose of the increment statement?

Why are increment statements a thing in for-loops in C++? To me it seems redundant, because you could simply put the increments inside the conditional code. Am I misunderstanding something important here?
To illustrate my question better, I'm including some pseudocode:
What is the difference between ->
for( int a = 10; a < 20; a = a + 1 )
{
cout << a << endl;
}
and
for( int a = 10; a < 20;)
{
a = a + 1
cout << a << endl;
}
It's more than mere convenience sometimes.
These are equivalent:
for (int a = 10; a < 20; a = a + 1) {
cout << a << endl;
}
for (int a = 10; a < 20; ) {
cout << a << endl;
a = a + 1;
}
But, these are not:
// this works ...
for (int a = 10; a < 20; a = a + 1) {
if (blah ...)
continue;
cout << a << endl;
}
// this doesn't
for (int a = 10; a < 20; ) {
if (blah ...)
continue;
cout << a << endl;
a = a + 1;
}
Since you're coming from python, an idiomatic for loop is like a python range, but much more powerful. Your C for loop, expressed in python would be:
for a in range(10,20,1)
It's more idiomatic to express this as:
for (a = 10; a < 20; a += 1)
Because the loop increment is 1, it's even more idiomatic to do this:
for (a = 10; a < 20; ++a)
But, for loops are:
for ([init_stmt]; [test_stmt]; [incr_stmt])
Where any of the *_stmt can be compound:
for (x = 0, y = 0; x < 10; ++x, y += 2)
Convenience.
However, your equivalent code should be:
for (int a = 10; a < 20;)
{
cout << a << endl;
a = a + 1;
}
It runs at the end of the loop body.
[ snips grumbling about quality of now deleted/ edited answers ;-) ]
This:
for (unsigned counter = 1; counter <= 10; ++counter) {
doStuff();
}
is largely equivalent to this:
unsigned counter = 1;
while (counter <= 10) {
doStuff();
++counter;
}
with the notable exception that, in the 1st case, you have the considerable benefit that counter is scoped only to within the for block and automatically goes out-of-scope as soon as it finishes - whereas with the latter, counter must remain in-scope after the loop, where it's potentially useless or even an obstacle.
(tangential: Note that C did not support within-for declaration, or any non-top-of-block declarations, until C99 - but barring extenuating circumstances, anyone not using at least C99 by now is making a questionable choice imho.)
edit: Craig also makes a very good point regarding continue - an oft-forgotten but certainly useful statement. I'm sure there are probably other differences we could conjure up.
for this example:
using namespace std;
int main(int argc, char** argv) {
for( int a = 10; a < 20;)
{
a = a + 1;
cout << a << endl;
}
return 0;
}
the output will be from 11-->20
the first example will be from 10-->19
your are putting the increment part outside the loop and this possible, but notice that the value 10 will not appear, because you are increment before printing the value of a
so in the 2nd example your printing the value and then increment, and at the end of the loop, you are quiting the loop without reaching 20, because the condition get you out the loop
executing code block before increment is the key for you, the for loop increment just after the code block is executed
Well it is not required, it is just for convenience.
In your second code, you made a little mistake which would make the code nonequivalent to the the first one.
Your increment should be at the end of loop in order to be equivalent to the first code
so it should rather be:
for( int a = 10; a < 20;)
{
cout << a << endl;
a = a + 1; //increment at the end of instructions
}
These little errors and also errors like forgetting to include your increment is why it is convenient to include the increment in the for loop.
Or you can use the while loop instead:
while (condition)
{//instructions here;}

Difference between pre and post decrement in recursive function argument

I have following sample code where i used pre-decrement
void function(int c)
{
if(c == 0)
{
return;
}
else
{
cout << "DP" << c << endl;
function(--c);
cout << c << endl;
return;
}
}
This function give output for input 4 as :
DP3
DP2
DP1
DP0
0
1
2
3
But when i use post decrement
void function(int c)
{
if(c == 0)
{
return;
}
else
{
cout << "DP" << c << endl;
function(c--);
cout << c << endl;
return;
}
}
Output goes in infinite loop with DP4
Can you explain me in detail why this happens ?
This happens because function(c--) will be called with the same value of c and when it finishes c will be decremented. But as it is recursively called, hence it will be called with same value with no chance of return and eventually you will hit stack overflow error.
Assume this, int x = 1, y = 0; Now y = x++ will result y == 1 and x == 2. But if you do y = ++x , then bot x and y will be 2.
Because --c will return c-1,however c-- return c.So when you use function(c--) is equal to function(c);c = c-1;.c will never be 0.So the function won't stop.
To know the difference between --x and x-- you can try the following code:
int x = 5,y=5;
cout<<x--<<endl;
cout<<--y<<endl;
cout<<x<<" "<<y<<endl;
In case of post decrement value will be passed before decrement , always same value will be passed to function , it never come out .
function(c--), first it call function(c) later decrement c-- will happen .