preference question

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int engima(int a, int& b)
{
    static int c = 0;
    c = a++;                       //why does it print 02
    b += 2;                                   //       412 and not 818
    return c * b;
}

int main()
{
    int x = 0;
    cout << x++; //prints 0
    cout << ++x << endl; //prints 2
    for(int k = 1;k < 3; k++)
    {
            cout << engima(k, x);   //k=1, print 8
    }                               //k=2, print 18
    
    system("pause");                                            
    return 0;
}
Last edited on
Write your question here.

No thanks. I "prefer" not to.
Last edited on
do you understand what the static keyword does?
do you understand what the reference argument does?

that is rhetorical I suppose; if you did, you would know why you get the result you got.
static variables are not destroyed when a routine ends, and their previous value is kept across function runs.

try this:
int foo()
{
static int x = 0;
return x++;
}
for(int z = 0; z < 5; z++)
cout << foo() << endl;

what do you get?

You should understand reference parameters by now, if they are covering static...
The code is not "enigmatic" (or "engimatic", whatever that is). It is "idiotic".
The result is the same whether 'c' is static or not since it is assigned the value of parameter 'a'.
And the post-increment of 'a' is pointless.
So "engima" could be equivalently written as:

1
2
3
4
5
int engima(int a, int& b)
{
    b += 2;
    return a * b;
}

And I assume "preference" was meant to be "precedence", even though that has nothing to do with it, either.
Last edited on
@dutch

First time c++
Can you elaborate on why a++ doesn’t have a higher precedence than direct assignment

++a gives 818
a++ gives 412
Last edited on
"Precedence" is only about the placement of invisible parentheses. I.e., if we always fully parenthesized expressions then "precedence" would not be needed.

The expression c = a++ is fully parenthesized as (c = (a++)), so yes, the post-increment has "higher precedence" than the assignment. But the value of a post-increment is the OLD VALUE of the variable, before the increment. So even though a will be incremented, the value of a++ is the value before the increment. It has nothing to do with "precedence". (It's kind of confusing, I guess.)
Last edited on
Topic archived. No new replies allowed.