简体   繁体   中英

Syntax for dereferencing a pointer in C (or C++)

I had a colleague check in code like this in C (syntax #1):

(*(*(*p_member).p_member).p_member).member

When I asked him why he didn't use -> (syntax #2):

p_member->p_member->p_member->member

he got really defensive stating that syntax #2 is more complicated than #1...I ended up changing his code because I had to modify it and couldn't read it, then he got mad that I actually touched it...

Which syntax does the SO community prefer? Both are valid, but I find syntax #2 more readable.

I'm setting this to community wiki due to the question being subjective.

The technical term for syntax # 1 is "nuts."

That said, I'd worry a little about code that has to go indirect 3 times too.

I think your coworker is either inexperienced, some sort of neophobe, or just plain ol' clueless. You're going to find that the unanimous choice is to use the -> syntax.

In C++ I would definitely use ->, because -> can be overloaded.

In CI would use -> as well because it's much easier to read, faster to type and less error prone (hope your colleague doesn't get lost in parenthesis!).

I'm typing off the cuff here, but my recollection is that the logic for the very existence of the -> operator in C was explained in the 1st edition of K&R as (paraphrasing): because otherwise you'd have to type (*p).a due to the necessary precedence of the * and . operators.

To not use -> for its intended purpose is nuts.

I'll take door #2, Monty! Sure its more difficult to type, but its more clear than finding out which operators dereference which pointer.

You may also wish to discuss the notion of "code ownership" in your team. You colleague does not "own" the code, the company does. Hence anyone employed by the company, with good reason, can edit it.

subjective huh ?

I'll take #2 as well!

The second variant obviously looks clearer. The only reason to prefer #1 is the case of some weird operator * and operator -> overloading when #1 has really different effect than #2.

Bad colleague. Change colleague.

我曾经遇到过“ - >”没有在几个编译器中正确实现的经验......所以当你有多个嵌套级别时,正常(* p).a更有可能工作。

No 2.

Having said that, don't offend people by changing their code, especially if it is a matter of style. It's just not worth it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM