Is top-level volatile or restrict significant in a function prototype?

后端 未结 4 1700
逝去的感伤
逝去的感伤 2020-12-11 21:19

Is there any practical difference between the following prototypes?

void f(const int *p);

void f(const int *restrict p);

void f(const int *volatile p);
         


        
4条回答
  •  悲哀的现实
    2020-12-11 21:58

    If there is nothing in the standard, then it's up to the compilers, but it seems that at least for gcc 4.9 (for x86) they are ignored. Check this small snippet that I've used to tease the compiler:

    static int b;
    
    void f(const int *p) {
      b = *p + 1;
    }
    
    int main()
    {
         int a = 42;
         const int *p = &a;
         f(p);
         return a;
    }
    

    If I compile it as is, I get

    f(int const*):
        pushq   %rbp
        movq    %rsp, %rbp
        movq    %rdi, -8(%rbp)
        movq    -8(%rbp), %rax
        movl    (%rax), %eax
        addl    $1, %eax
        movl    %eax, b(%rip)
        popq    %rbp
        ret
    main:
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $16, %rsp
        movl    $42, -12(%rbp)
        leaq    -12(%rbp), %rax
        movq    %rax, -8(%rbp)
        movq    -8(%rbp), %rax
        movq    %rax, %rdi
        call    f(int const*)
        movl    -12(%rbp), %eax
        leave
        ret
    

    If I compile it using void f(const int *__restrict__ p) I get

    f(int const*):
        pushq   %rbp
        movq    %rsp, %rbp
        movq    %rdi, -8(%rbp)
        movq    -8(%rbp), %rax
        movl    (%rax), %eax
        addl    $1, %eax
        movl    %eax, b(%rip)
        popq    %rbp
        ret
    main:
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $16, %rsp
        movl    $42, -12(%rbp)
        leaq    -12(%rbp), %rax
        movq    %rax, -8(%rbp)
        movq    -8(%rbp), %rax
        movq    %rax, %rdi
        call    f(int const*)
        movl    -12(%rbp), %eax
        leave
        ret
    

    Anf finally if I compile it using void f(const int *__volatile__ p) I get

    f(int const*):
        pushq   %rbp
        movq    %rsp, %rbp
        movq    %rdi, -8(%rbp)
        movq    -8(%rbp), %rax
        movl    (%rax), %eax
        addl    $1, %eax
        movl    %eax, b(%rip)
        popq    %rbp
        ret
    main:
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $16, %rsp
        movl    $42, -12(%rbp)
        leaq    -12(%rbp), %rax
        movq    %rax, -8(%rbp)
        movq    -8(%rbp), %rax
        movq    %rax, %rdi
        call    f(int const*)
        movl    -12(%rbp), %eax
        leave
        ret
    

    So it seems that in practice they are ignored in C as well.

提交回复
热议问题