Thread: sizeof()

  1. #1
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    169

    sizeof()

    I've always wondered how the
    Code:
    sizeof()
    operator works. So, I googled how it works but everything that I saw in the first two pages was basically useless to what I mean by my question. All websites explain a tutorial on "what sizeof() does" and "how to use sizeof()" but none of them came close enough to explaining how it works.

    Does it already have the values of int , float, etc. saved for use or does it calculate it each time when used?
    How does it calculate the size of a string? Does it count the number of places/bytes till it encounters a 0 character? If so, wouldn't it take up some processing time if the string is quite long (therefore, leading me to conclude that it doesn't count the number of bytes for each time it is associated with a string)?

    Let's say I wanted to make a function does everything what sizeof could do. Could someone tell me what we'd be looking at and how something like this should be approached?

    I am a little bit inexperienced when it comes to programming due to my lack of interest in learning C++ at school for the first few months but as time passed by, dedicating myself to learning C++ and programming in general is the only thing I want to do at this point of time between having to study other subjects (Phy, Chem, Math etc though I do love Math) and learning programming. I intend to write my own program features like string manipulation, vectors, etc by thr end of this year (I think I know how to approach it but I'll ever know unless I start trying and if, or when, I fail, it would be a good learning experience popping back on here and getting my doubts cleared).

  2. #2
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,656
    The compiler has it saved internally.
    Here is one example: clang/TargetInfo.h at master * llvm-mirror/clang * GitHub

    Let's say I wanted to make a function does everything what sizeof could do
    Why do you want to do this?

  3. #3
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    169
    Curiosity to learn? Well, obviously not just that but because I actually want to know how operators are actually used. sizeof() seemed to be an interesting choice to me. Also, I started looking at more and more of assembly code recently and when I saw what happens at sizeof, it was just a movl which basically just moves the value into a register (the 'esl' one, or so, I guess? But I don't remember that so I'll need to take another look). This led me to thinking that the sizes of int, float, etc are pre-stored but that can't be true because let's say you put in a string, there must be an algorithm through which it calculates the size rather than just doing something along these lines (which was my first thought)

    Code:
    while ( *(str++) != '\0' )
    {
         size++;
    }
    return size;
    
    //time complexity would increase if string was long and also I read somewhere that sizeof() is performed in compile-time or something like that
    //so if I enter a string in run time and then have a statement somewhere later in the program saying sizeof(str), how would it be determining it
    //Gradually, I was derailed off my original lines of thought which brought me here to ask the question
    So, why and how exactly does it work would be my question in short?

  4. #4
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    657
    sizeof gives you a compile-time constant value because the compiler knows how big all objects or types are at compile time. So if your code says "sizeof (int)", the compiler will effectively replace that with "(size_t)4" (assuming "sizeof (int)" is 4 on that particular implementation). Strings are the same: 'sizeof "foo"' gives you a compile-time value of 4 because the compiler knows that "foo" is 4 chars in size (3 chars plus the null terminator).

    Note that code like the following is completely safe (the null pointer is not dereferenced) because sizeof doesn't evaluate its operand; it only returns its size:

    Code:
    char *foo = NULL;
    size_t s = sizeof *foo;
    In that code, s == 1 because "sizeof (char)" is 1 by definition.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,234
    Quote Originally Posted by Zeus_
    //time complexity would increase if string was long and also I read somewhere that sizeof() is performed in compile-time or something like that
    //so if I enter a string in run time and then have a statement somewhere later in the program saying sizeof(str), how would it be determining it
    The result of sizeof is the size of the type of its operand, or the operand itself if it is a type name. Hence, sizeof(str) results in the size of the type of str. If str is an array of 20 char, then sizeof(str) is 20, even if the null terminated string stored in str is "hello" (i.e., a string of length 5). If str is a pointer to char, then sizeof(str) results in the size of a pointer to char, regardless of what str points to. If str is a std::string, then sizeof(str) results in the size of a std::string object, even if str.length() might return a different value.

    The runtime time complexity of sizeof is constant time because the compiler has done all the hard work in determining the size at compile time, so there's nothing to do but load and use the size at runtime. But this is why sizeof cannot give you the length of a null terminated string read at runtime: that would require doing the same thing strlen does, which cannot be done at compile time because the string value is unknown at compile time. However, the compiler does have to compute the length of a string literal at compile time, but that's part of the compilation process.

    The reason why you don't find so many resources telling you exactly how sizeof works is because that is implementation detail: compiler authors are free to implement sizeof as they see fit, as long as the compiler meets the requirements imposed on what sizeof should do.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    169
    I tried a few examples last night and realised that sizeof() behaves differently compared to what I was expecting. Your explanation supports the outputs I noticed.

    > If str is a pointer to char, then sizeof(str) results in the size of a pointer to char, regardless of what str points to. If str is a std::string, then sizeof(str) results in the size of a std::string object, even if str.length() might return a different value.

    Makes sense and supports the outputs which I saw. Thanks again @laserlight!

  7. #7
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,490
    Quote Originally Posted by Zeus_ View Post
    I tried a few examples last night and realised that sizeof() behaves differently compared to what I was expecting. Your explanation supports the outputs I noticed.
    It's good that you now understand. I think it's important to keep in mind, though, that sizeof is an operator not a function (I guess that by you writing sizeof() seems to indicate, to me, that perhaps you think it's a function or at least you're thinking of it being like a function).

  8. #8
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    169
    Nah, I do know it's an operator like, say, +, -, etc. I think I mentioned stating what I know about sizeof clearly in my first post (7th word). Also, I know that operators have a different colour on all (probably?) IDE's so it's out of question that I thought it's a function.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 12-09-2010, 02:33 PM
  2. A different sizeof()?
    By hugo2x in forum C Programming
    Replies: 9
    Last Post: 10-18-2009, 12:23 PM
  3. Replies: 6
    Last Post: 10-15-2007, 08:05 AM
  4. sizeof(cin) and sizeof(cout)
    By noobcpp in forum C++ Programming
    Replies: 11
    Last Post: 06-30-2007, 11:00 AM
  5. sizeof help
    By saahmed in forum C Programming
    Replies: 2
    Last Post: 03-08-2006, 06:37 PM

Tags for this Thread