How to check size of structure during development in Visual C++?

Jul 2015

How to check size of structure during development in Visual C++?

Today I wanted to know what is sizeof(SomeStructure) during my coding in C++ in Visual Studio, without compiling and running my program. I needed that to put it into an assertion. Sure I could run the program and then break into debugger and evaluate the sizeof(SomeStructure) e.g. in Watches window, but the project is big and takes long time to build.

It turns out there is no such feature in Visual Studio to check size of structure, but it can be easily hacked using IntelliSense. In just few seconds, from this Google query, through its first result - this StackOverflow page, I have found following solution:

1. Put this line somewhere into your code:

template<size_t S> class Sizer { }; Sizer<sizeof(MY_STRUCTURE)> foo;

2. Replace "MY_STRUCTURE" with the name of your structure, other type or a variable.

3. Hover mouse cursor over "foo" and observe evaluated expression, for example: "Sizer<1296U> foo". 1296 is the size of your structure, in bytes - same as operator sizeof would return in runtime, when your program is compiled in currently selected configuration. "U" is for "unsigned".

By the way, maybe it would be a good feature request to add printing size of a type to the information available in design-time in Visual Studio, e.g. to Properties window, where there already are information about the type like IsTemplate, IsValue etc.?

Comments (2) | Tags: c++ visual studio | Author: Adam Sawicki | Share


Łukasz Mendakiewicz
2015-07-08 22:52:20
It's even easier in Visual Studio 2015 -- enter "sizeof(MY_STRUCTURE)" in any semantically valid location (e.g. in a function scope) and Quick Info (hover or press Ctrl+K,Ctrl+I) will display the size.
I don't use Properties window, but if you think this would be valuable to you, please enter the request through Send-a-Smile.
Jacek Jankowski
2015-08-18 11:16:24
It is very helpful info Adam, thanks. Just be careful when you use #pragma pack - then you have to run your program to evaluate the real size of your structure..

Post comment

Nick *
Your name or nickname
Your contact information (optional, will not be shown)
Text *
Content of your comment
Calculate *
(* - required field)
STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2017 Adam Sawicki
Copyright © 2004-2017 Adam Sawicki