Interview Question
Software Engineer / DevelopersCountry: United States
Yes. Compilers have become much smarter as compared to when this interview question was first created. Clueless interviewers still continue to use that though...
Suppose p is allocated dynamically, e.g., char *p=(char *)malloc(size), so compiler won't know the address of p until runtime.
You may find the answer with disassebmly code..
They are same, at least for the g++ I used.
Here is a sample c++ code test.cc:
int main()
{
const char *p = "hello";
L1: char c = p[2];
L2: char b = *(p+2);
L3: {}
}
~
g++ -S test.cc, and you get:
.file "test.cc"
.section .rodata
.LC0:
.string "hello"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movq $.LC0, -16(%rbp)
.L2:
movq -16(%rbp), %rax
addq $2, %rax
movzbl (%rax), %eax
movb %al, -2(%rbp)
.L3:
movq -16(%rbp), %rax
addq $2, %rax
movzbl (%rax), %eax
movb %al, -1(%rbp)
.L4:
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
you can see the generated code for p[2] and *(p+2) are same.
USELESS question. Why are they asking this?
They are absolutely equivalent in every way. An early phase of a compiler will convert a[i] to *(a+i).
It gets mapped to same executable code.
In fact, most compilers would even accept 2[p] because it gets converted to *(2+p) which is *(p+2). Unless the compiler maker put useless extra checks to exclude this.
BTW, this is a useless interview question.
*(p+2) is more efficient...
lets the start address is 1000, *(p+2) will add 2 to base address and fetch the data at address location 1002... this one fetch the data in single step
where as p[2] move one by one location from base / start address to the desired address 1002, this one fetch the data in n steps (for p[n])
"where as p[2] move one by one" why do you say this? i've never seen such argument before. that's not how it works in arrays
When an array is declared in the stack or heap, those 2 statements are equivalent since the compiler translates p[2] in *(p + 2 * sizeof(char)) = *(p + 2 * 1) = *(p+2) since 2 and 1 are constants.
- Miguel Oliveira September 10, 2013String literals are usually stored in read-only segments of memory. So the compiler might know the value of p during compile time. This still does not make a difference in efficiency between the 2.