ivanlw
V2EX  ›  问与答

C++指针的星号应该放哪边?int* p还是int *p呢……头痛好多年了……还有int* test();还是int *test();

  •  
  •   ivanlw · Sep 26, 2013 · 6929 views
    This topic created in 4786 days ago, the information mentioned may be changed or developed.
    11 replies  •  1970-01-01 08:00:00 +08:00
    timonwong
    timonwong
    Sep 26, 2013❤️1
    1
    我的习惯

    变量声明放右边:
    int *p1, *p2, *p3;

    返回值放中间:
    int * test()
    jedyu
    jedyu
    Sep 26, 2013
    2
    int *p = NULL;

    int* test();
    iLluSioN
    iLluSioN
    Sep 26, 2013
    3
    为了避免类似的纠结,常年放中间。。。
    GordianZ
    GordianZ
    Sep 26, 2013
    4
    放右边,好区别下面两种:
    int *p1, *p2, *p3;
    int* p1, p2, p3
    ivanlw
    ivanlw
    OP
    Sep 26, 2013
    5
    @GordianZ 这样子好理由!如果是函数返回值你怎么处理呢?
    yujnln
    yujnln
    Sep 26, 2013❤️2
    6
    1. int* p; // legal but might be misleading

    We say that this definition might be misleading because it suggests that int* is the
    type of each variable declared in that statement. Despite appearances, the base type
    of this declaration is int, not int*. The * modifies the type of p.

    2. int* test(); // func returns a pointer to int
    angelface
    angelface
    Sep 26, 2013
    7
    这个没有定论放在哪边好, 大牛们也是各有各的写法,但我倾向说放左边,这样从语音上比较合理
    int* p;一个指向int型的指针p,放在右边像是在取值。
    46fo
    46fo
    Sep 26, 2013
    8
    我有变量名的 习惯放右边 没得放左边
    sinxccc
    sinxccc
    Sep 26, 2013
    9
    放中间或者放右边,放左边太容易歧义了,星号不是用来修饰类型,而是用来修饰变量的。
    jiangtao92
    jiangtao92
    Sep 26, 2013
    10
    其实放在左边也是会出现歧义,以为int* 是一个类型,例如 int* a,b;
    a 是指针,b 还是int。。
    julyclyde
    julyclyde
    Sep 26, 2013
    11
    从语法上应该是
    int *p, i;
    声明一个p指针和i变量

    从语义上讲,p指向一个int,所以int修饰的是*p
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1400 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 22:52 · PVG 06:52 · LAX 14:52 · JFK 17:52
    ♥ Do have faith in what you're doing.