2

Suppose we have a line in which is an array definition:

char v[100];

What is the subsequent of evaluating this definition? I think that char v definition evaluated first and further to uninitialized variable v operator [] is applied. But it is nonsense. I want to understand, why this definition returned the char*. Please give if it possible references to spec.

6
  • C-style char[] arrays always will be decayed to simple char* pointers, when passed as function partameters. Commented Apr 19, 2014 at 17:24
  • 1
    It's just a declaration, like int i;. No part is "evaluated". Commented Apr 19, 2014 at 17:26
  • @πάντα ῥεῖ Does it mean that char v[100] is just syntactic sugar? Commented Apr 19, 2014 at 17:26
  • 1
    @Dmitrii, It is when used as a function parameter, but not otherwise. Commented Apr 19, 2014 at 17:27
  • 3
    This is a variable declaration. There is no statement or expression here, hence nothing needs to be evaluated. char v[100] = "abc" would be evaluated, v[3] = 'd' would be evaluated, return v[4] would be evaluated... But not this. Commented Apr 19, 2014 at 17:32

1 Answer 1

2

char v[100] is a variable declaration.

There is no statement or expression here, hence nothing needs to be evaluated.

char v[100] = "abc" would be evaluated.

v[3] = 'd' would be evaluated.

return v[4] would be evaluated.

But not char v[100].

For example, here is how char v[100] = "abc" is evaluated by the Microsoft Visual C++ compiler:

    char v[100] = "abc";
001B1DA8  mov         eax,dword ptr [string "abc" (1B695Ch)]  
001B1DAD  mov         dword ptr [ebp-6Ch],eax  
001B1DB0  push        60h  
001B1DB2  push        0  
001B1DB4  lea         eax,[ebp-68h]  
001B1DB7  push        eax  
001B1DB8  call        @ILT+135(_memset) (1B108Ch)  
001B1DBD  add         esp,0Ch  

You can view the disassembly of char v[100] for yourself, and see that there is "no code behind it".

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. Consider a simple declaration int i on the stack. When the compiler sees that, doesn't it have to add assembly code to move the stack pointer forward by the size of an int to make space for the int now on the stack?
@Dan Nissenbaum: To the best of my knowledge, the compiler will translate every occurrence of i within an operation, such as x=i+j for example, into the address of i (which is an address within the stack). The SP register itself will "move up and down" only during runtime, when these operations are executed.
@DanNissenbaum When you enter the function, enough space is pushed into the stack for all its local variables. See for example the x86 ENTER instruction. The SP and BP are only adjusted during ENTER & LEAVE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.