Amazing C++


Somewhat subconsciously, in a hurry, I wrote the below statement

char command[MAX_QUERY_SIZE] =
"select top 300 "
    "log.InsertsType, log.Inserts, log.Id, log.ProcessId, "
    "log.ThreadId, log.Level, log.MessageNumber, "
    "log.Time, log.MessageGuid, comp.Component, "
    "pool.Fqdn as Pool, machine.Fqdn as Machine "
"from cls.dbo.Log log, cls.dbo.Component comp, "
    "cls.dbo.Fqdn pool, cls.dbo.Fqdn machine "
"where log.ComponentId = comp.Id and log.PoolId = pool.Id and "
    "log.MachineId = machine.Id "
    "and not (comp.Component like '%test%')";

built, run. All fine.

A day later the statement caught my eye. I thought something is wrong with it; how come it even compiles? Is it really a valid statement?

So, after a little research I found that yes, this is one of the official ways to initialize an array of characters. Albeit being used quite rarely: people reasonably prefer either “char* command” variation, OR lstrcpy[A], OR StringCchCopy[A]. But yet, the block initializer works too(!) and it is the language-compliant construction.

So, what is the resulting machine code? Actually, it’s very, very good – I would not write better by hand. First, the text constant is copied, very efficiently, to the “command” field. This is done by hardware loop command, and at each loop iteration a block of four bytes is moved.

Then, the remaining part of the “command” buffer is filled with zero bytes via the old good memset. Here is what is happening in detail. Just great.

PS: This is MS C/C++ compiler, included in VS 2010.

000d4351 b967000000    mov ecx,67h
000d4356 be786c0e00    mov esi,offset clsview!`string' (000e6c78)
000d435b 8dbdb0fbffff  lea edi,[ebp-450h]
000d4361 f3a5          rep movs dword ptr es:[edi],dword ptr [esi]
000d4363 66a5          movs word ptr es:[edi],word ptr [esi]
000d4365 684a020000    push 24Ah
000d436a 6a00          push 0
000d436c 8d854efdffff  lea eax,[ebp-2B2h]
000d4372               50 push eax
000d4373 e8c3cdffff    call clsview!ILT+310(_memset) (000d113b)

Isn’t the C++ great, and the VC 12.0 compiler real great? I think yes.

Comments (0)

Skip to main content