Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is &&&& operation in C [closed]

int main()
{
        int i, c;
i:
        for (i = 0; i < 3; i++) {
                c = i &&&& i;
                printf("%d\n", c);
        }
        return 0;
}

The output of the above program compiled using gcc is

0
1
1

How is c evaluated in the above program?

like image 887
manav m-n Avatar asked Dec 19 '12 07:12

manav m-n


2 Answers

In this case it's also parsed as && and &&. First one is logical AND but second && is the address of label i not the address of variable i. (it's gcc extension)

This will be parsed as c = (i) && (&&i); // parenthesis is just to make it human readable.

& gives you the address of variable i. Which you have just asked few minutes ago in this question .

For more about the address of label and values see this gcc extension.

EDIT : since && logical AND always follows the short-circuiting of statement.Hence in first case it will be 0 since it found i=0 so it won't go to &&i(the second part of logical expression).

But in all subsequent cases , i is not 0 so it will give TRUE and will go to next expression &&i which is address of label i (And Address of i will always evaluate to TRUE.)

So the result of the full expression will always be TRUE means 1 except the first case where i is 0. Hence you are seeing the result

0
1
1
like image 133
Omkant Avatar answered Oct 01 '22 14:10

Omkant


The use of labels as values is a gcc extension (see here). Your expression segment:

c = i &&&& i;

equates to: c = i && (&&i); where &&i is the address of the label i.

Keep in mind you're combining two totally different i "objects" here. The first is the i variable which cycles through 0, 1, 2, while the second is the label i, for which the address is always some non-zero value.

That means that the result placed in C will be 0 (false) only when the variable i is 0. That's why you're getting the 0, 1, 1 sequence.

As an aside, I give serious thoughts to "employee management practices" if one of my minions bought me code like this for production use. Anything that removes the possibility of monstrosities like this would be a good thing in my opinion :-)

like image 38
paxdiablo Avatar answered Oct 01 '22 12:10

paxdiablo