i run the below code and surprised to see the o/p .

take a look and let me know whats happenning there.

#define print(x) printf(#x"=%d\n",x)
int main(){
        int a[10];
        print(a);
        print(*a);
        print(*a+1);
        print(*a+3);
        print(*a+1-*a+3);
        return 0;
}

Out Put:

[Zonnie@telnet CPz]$gcc funny.c
[Zonnie@telnet CPz]$ ./a.out
a=-1073745776
*a=1
*a+1=2
*a+3=4
*a+1-*a+3=4

regardless of whatever stores at a shouldn't it produce -2.

whats the story ?

* (unary, dereferencing) has higher precedence than addition or subtraction, so it's like (*a)+1-(*a)+3.

Because (a+1)-(a+3) and a+1-a+3 are not the same.

http://mathforum.org/library/drmath/view/58772.html

suppose say a = 2000 and
a[0] is 1

i.e *a = 1

then *a + 1 = 2;
and *a + 3 = 4;
so now
*a + 1 - *a + 3 = 2 - 4 = -2

* (unary, dereferencing) has higher precedence than addition or subtraction, so it's like (*a)+1-(*a)+3.

(*a) + 1 = *a + 1
(*a) + 3 = *a + 3

no, like wingless said a+1-a+3 not equal to a+1-(a+3)
I'm not sure what your assumptions are...

As stated above, the priority is the same across the entire line, so it just runs the equation from left to right.

*a + 1 - *a + 3

assuming *a = 1, it now looks like

1+1-1+3, which going in order proceeds as follows:

1+1-1+3 = 2-1+3 = 1+3 = 4

You seem to believe that *a + 1 - *a + 3 = (*a + 1) - (*a + 3), which if that were the case, would in fact = -2 because the parenthesis would change the order in which the parts were calculated. With parenthesis, this is what happens.

again assume *a=1:

(1+ 1) - (1+ 3) = 2-(1+3) = 2-4 = -2

>regardless of whatever stores at a shouldn't it produce -2.
I dont really see why do you expect those values. When you dereference a, you will get junk jusy because you haven't initialised it. When you didthis *(a+1), it was getting the address of a thats the base address and the adding one to it. It other words its called relative addressing. The point a itself is not moved to a+1.

Try initialising a values and try it back again like as follow

#define print(x) printf(#x"=%d\n",x)

int main()
{
        int a[10];
        a[0] = 10;
        
        print(a);
        print(*a);
        print((*a)+1);
        print((*a)+3);
        print((*a)+1-(*a)+3);
        
        getchar();
        return 0;
}

~ssharish

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.