Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is *++*p acceptable syntax?

Tags:

c

In K&R Section 5.10, in their sample implementation of a grep-like function, there are these lines:

while (--argc > 0 && (*++argv)[0] == '-')
    while (c = *++argv[0])

Understanding the syntax there was one of the most challenging things for me, and even now a couple weeks after viewing it for the first time, I still have to think very slowly through the syntax to make sense of it. I compiled the program with this alternate syntax, but I'm not sure that the second line is allowable. I've just never seen *'s and ++'s interleaved like this, but it makes sense to me, it compiles, and it runs. It also requires no parentheses or brackets, which is maybe part of why it seems more clear to me. I just read the operators in one direction only (right to left) rather than bouncing back and forth to either side of the variable name.

while (--argc > 0 && **++argv == '-')
    while (c = *++*argv)
like image 676
The111 Avatar asked Dec 10 '22 03:12

The111


2 Answers

Well for one, that's one way to make anyone reading your code to go huh?!?!?!

So, from a readability standpoint, no, you probably shouldn't write code like that.

Nevertheless, it's valid code and breaks down as this:

*(++(*p))

First, p is dereferenced. Then it is incremented. Then it is dereferenced again.


To make thing worse, this line:

while (c = *++*argv)

has an assignment in the loop-condition. So now you have two side-effects to make your reader's head spin. YAY!!!

like image 104
Mysticial Avatar answered Dec 11 '22 15:12

Mysticial


Seems valid to me. Of course, you should not read it left to right, that's not how C compiler parses the source, and that's not how C language grammatics work. As a rule of thumb, you should first locate the object that's subject to operating upon (in this case - argv), and then analyze the operators, often, like in this case, from inside (the object) to outside. The actual parsing (and reading) rules are of course more complicated.

P. S. And personally, I think this line of code is really not hard to understand (and I'm not a C programming guru), so I don't think you should surround it with parentheses as Mysticial suggests. That would only make the code look big, if you know what I mean...

like image 36
Violet Giraffe Avatar answered Dec 11 '22 17:12

Violet Giraffe