Well, most mainstream languages at least specify their char size, and/or have very few constructs that require knowing its size. C does not specify the size of a char, and you frequently need the sizes of your types.
(That said, as pointed out by other comments, sizeof itself is in units of char, so sizeof(char) is necessarily 1.)
There are no other good languages. To the extent they have anything good they are calling libraries written in C. The only other worthwhile languages are pure machine level code that must be expressed as a gate level circuit diagram.
You cannot fit them into a single char, and you have to use a string instead. They're represented using a surrogate pair, which is similar to the continuation bytes of utf-8 except you never need more than two code points (hence "pair").
JS is a bit weird in this regard, because it also knows true codepoints. You just have to know which operations are "unicode safe". Or rather "astral plane safe".
UTF-16 was a mistake, and it's maddening that several big ecosystems went with it. You get all the complexity of UTF-8, but it also takes up more space in the "average" case since a huge majority of text is in the "ASCII overlap" portion of unicode.
There's u8string, etc. Now the std library might not have much of anything to deal with encoding, but that doesn't make the types useless. Other libraries can use them.
I mean C# was inspired mainly by Java and C++, from which Java is a C-style language and C++ is a direct expansion of C (or at least started out as one). JavaScript and Java both have similarly looking syntax on account of both being C-style languages, but that's where the familiarities stop.
So saying this is like saying your grandson has as much to do with you as your two neighbours who like your style enough to copy it have to do with each other - your grandson may feel as different from you as the neighbours from each other, but that's because the family tree has acquired new genetic material through your wife and your son-in-law, and the times have changed so his behaviour is different - and not because he actually doesn't have anything to do with you.
This meme doesn't mention any languages. Like many memes on this sub, it's about a specific language, and it's up to you and your knowledge of programming languages to figure out which one is being talked about. Just because the meme is not about C# doesn't mean that everyone forgot that C# exists.
That's because Microsoft was going to make a .NET version of Java that was incompatible with standard Sun Java (the standard embrace, extend, extinguish playbook), then got sued over it (twice). C# is what fell out the other side of that fight.
Ok I should have specified the unanswered but whys* that's on me
For example the sort function in js that sorts based on strings. No valid answer to "but why" other than retrocompatibility
Whereas if you look low level, instructions on any arch usually have a justification like "makes the arch scalable" or "allows for a faster hardware implementation"
Welcome to the wonderful world of C#, which uses utf-16 for strings.
If they just called them type "string", everything would be okay. But to have the audacity to call them type "char" and have them be two bytes? Blasphemy!!
The whole, "never know what the future holds", may not necessarily be true for this, but... do I have a story for you that makes this sort of defensive programming my default now, even if the docs promise one thing.
Back in the day, I was working on a project that made some HTTP request to a payment service (In C#). It was hosted on an Azure App Service, and it was running absolutely fine.
In a code review, someone mentioned "Maybe we should force this to a specific TLS version, just incase". I looked up the docs, and given our versions, and (assumed) machine, it wasn't an issue. C# would try TLS 1.2, 1.1, then SSL3, in that specific order. You could "edit the registry" to swap the order, but when would that ever happen right? (You probably see where this is going). We were using Azure App Services which don't allow you to edit the registry anyway so what does it matter. I was in a rush, so pushed back against the code review and through we went.
Now, and this is a complete guess, but it lines up. Right at the same time, the Spectre vulnerability was released, and it forced basically everyone to "patch" their CPUs.
A week later, suddenly all payments start failing and it's impossible to figure out why until... well it seems like it's using SSL3?!? What the hell? OK let me write some diagnostics, redeploy (via a Staging slot), and check. After redeploy, it was back to TLS 1.2 as the default!?
My theory is this. Microsoft was forced to update more machines than they normally would to patch Spectre. In doing so, they had to roll customers using App Service (Remember, we can't see the underlying machine) onto really old machines or possibly even machines with fked up config, and so we ended up with a machine that had SSL3 as the default. When I redeployed, because I went via a Staging slot, it was a different machine, and so by the time I tested again, we were back to normal.
I never ever heard the end of it either. "I told you in that code review".
I've reached the point where I see that sort of eternal "I told you so" no longer as annoying, but a good way to have a lesson stick for longer (especially if others hear about it).
sizeof is more like an operator than a function. You can actually write sizeof without braces. There's nothing to optimize out, it's by design a compile-time constant expression. It's like a fancy way to write a scalar.
sizeof is mandatory consteval, it must be evaluated at compile time. (More specifically, it's a keyword that tells the compiler to insert the named type's size, which the compiler will have in memory if the type is defined. It's essentially a post-preprocessor "compiler macro", so to speak.)
You can use it anywhere the compiler expects a constant expression, as this ugly jank shows:
// Control values.
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, };
// Sizeof thing. sizeof(Charception<N>) == N for all nonzero Ns.
template<size_t N>
struct Charception : Charception<N - 1> {
char c;
}
template<> struct Charception<0> {};
// Proof values.
#define CC(a) sizeof(Charception<a>)
int rra[] = { CC(1), CC(2), CC(3), CC(4), CC(5), CC(6), CC(7), CC(8), };
#undef CC
// Sanity checks.
for (int i = 0; i < 8; i++) { assert(arr[i] == rra[i]); }
assert(arr[sizeof(Charception<7>)] == rra[7]);
// For more intentionally-bad jank proof of this, see:
// https://www.ideone.com/hDJRVC
// Bring your own compiler, ideone somehow doesn't have a C++17 compiler yet.
// Bring your own eye bleach, I did a good bit of variadic ugliness just for fun. It's hideous and relaxing! ^_^
Note: sizeof is usually the same in both C & C++, so all of this applies to C, too. There is one gotcha, though: It's a runtime operator if you use it on a VLA, and only if you use it on a VLA. (C-only rule, C++ doesn't have C-style VLAs.)
Edited because I forgot the Charception<0> base (it's kinda super-important, the universe breaks if we don't have it), and because I forgot a sizeof.
Although I don't think it's UB. Preprocessor will do what it's asked for, and it doesn't know shit about the compiler reserved words. Then the output of the preprocessor is either valid, or invalid, but everything is 100% predictable. By the way, some standard libs/runtime are happily redefining the "new" operator in order to include debug information about the allocation context for reporting memory leaks (e.g. MSVC standard libs), and this can be done in a totally c++ standard compliant way, that will be accepted by all compilers. I did it myself a couple of times.
Definitely. For example, I always use malloc(size*sizeof(char)) to ensure that it's doubly obvious (Since I rarely need to malloc outside of a declaration) that I intend to store characters in the resulting buffer even if that multiply does nothing (plus the compiler will likely optimize it out anyway).
Eventually, a "char" might be redefined for utf-8 to accommodate a diverse range of writing systems, which means a char is usually 1 byte but potentially up to 4 bytes.
For context, I'm working on code with an initial commit from the 90s. Future proofing isn't a terrible idea.
This would be considered a breaking change for C/C++ and it is extremely unlikely they would ever do this. They’d probably add a new type like utf_char_t (or utf8_char_t, utf16_char_t, utf32_char_t) and UTF-aware string functions to the stdlib.
If Unicode has taught us anything, it's that mixing sized types with encoding interpretation is a bad idea. Char is established as a byte by now after 50+ years or so, but it wouldn't be called that if designed today, because a character has no fixed size. If you want to represent an Unicode code point, write a view type that points into a span of chars, and use the right function/class/whatever to work with the representation.
Yeah, the real issue is that almost always what you care about with Unicode (on the parsing side, anyway) are “grapheme clusters”, which can consist of multiple code points. And both of those map poorly at best to ‘characters’ or ‘bytes of memory’.
If your code base use macros to redefine what char means, wtf is wrong with your team? If not, sizeof(char) will ALWAYS return 1, no matter how many bits is in a char. That's because sizeof doesn't give you the size of a type in bytes, it gives you the size in number of chars
If the violation of standards compliance is such that a fundamental presumption that a char is 1 byte cannot be relied on, then there isn’t much point in marketing that as a C compiler, because it simply cannot properly compile basic C code. AFAIK not a single compiler has ever done this.
What is true today may not be true tomorrow. Using sizeof is better as it protects against changes to the underlying specs or a change to the data type.
C really tries to avoid any breaking changes between versions. Changing this would be such a fundamental change of the language I don't think you could still call it C. If you want to plan for a change as fundamental as this you might as well plan for the semantics of sizeof() changing or it getting removed. At that point all bets are off anyway.
Which is why i also qualified it with a data type change. The point is that sometimes changes happen and having code in place that preemptively deal with those changes is a hallmark of elegant design and implementation.
An unsigned char will be able to represent any value from 0 to 255, eg your usual ascii character. A signed char will be able represent any value from -127 to 127.
( Someone fact check me on this but i think that's it ) (edit : -127 to 127, the extra value "-128" is usually implemented but not guaranteed by the C standard)
ASCII is hardly the only character encoding, and unsigned char often doubles as a byte type. It’s also also a numeric type if you only need a small range and need to pack your data tight
char is 8 bits because memory is addressed in 8 bits, and 7 bits would be... Awkward. And this bit was in the end used for parity checks, and later for extended encodings.
Putting the example here so the explanation isnt overloaded :
signed char a_hundred_signed = 100;
unsigned char a_hundred_unsigned = 100;
signed char fifty_signed = 50;
unsigned char fifty_unsigned = 50;
signed char r_signed = fifty_signed - a_hundred_signed; // will yield -50
unsigned char r_unsigned = fifty_unsigned - a_hundred_unsigned; // will yield 206 because it wraps around the max value of 256
An unsigned char is an integer type that gives you *at least* the value range 0 to 255. A signed char is an integer type that gives you *at least* the value range -128 to 127.
sizeof(char) is always 1 by definition because a char is one byte. The nuance is that a byte doesn't need to be 8 bits in C/C++, it needs to be at least 8 bits.
In C char is just a number, as a character depends on the encoding. So signed char is a number from -128 to 127 and unsigned char is from 0 to 255 (for 8 bits per byte)
it's a data type with a size of 1 byte. useful if you want to store a boolean value (since it's the smallest simple data type) or a character (since it's big enough to store 7-bit ascii)
they're usually used to store strings; the following allows you to take up to 99 characters of user input (initialises array of chars then writes the input into the array)
#include <stdio.h>
int main(void){ char string[100]; scanf("%99[^\n]", string); }
strings in c must be null-terminated so we need to leave the last position free for the byte '00000000' so we know where the string ends when we try to read it. that's why we can't take 100 characters here
we also have this for bools that more closely resemble those in the more abstract languages. internally, any non-zero number (most usefully, 1) is interpreted as true and 0 is interpreted as false. we can then use boolean algebra to construct and simplify our conditions
C++ standard guarantees that char is at least 8 bits. Pretty much all data models use 8 bits for char, but it doesn't mean that some weird architecture could not use more.
That's CHAR_BIT then, sizeof(char) is always 1 even if you have 16 bit chars. Nothing can be smaller than char in general, you can see sizeof as an operator returning sizes as number of chars, basically
it's not so much a "just in case" and more a "self-documenting code". A hardcoded 1 give you a value. a sizeof(char) give you the value and tell you why it's 1.
And it's more consistant with the rest of the code. if you write sizeof(int) for int, sizeof(long) for long, and 1 for char. it's weird and ugly.
also, if you one day decide to switch char for something else, you will look everywhere you wrote char, and miss that hardcoded 1.
(in many cases, the size is used as multiplicative, so "hardcoded" will mean omitting the value entirely, rather than explicitly writing *1, which make thing worse.)
sizeof() evaluates to a constant value during compile time so what, it takes 0.0000001 seconds more during compilation? just use sizeof even if the specification guarentees it's always size 1
i guess the point the guy in the middle would make is that *sizeof(char) is just "multiply by 1", and hence it's just redundant clutter that makes the code less readable
a valid counterpoint to that, of course, is that it can clarify intent that the number in context specifically represents a count of bytes, but yeah lol
The problem is that there is no good definition of byte. Traditionally, it was the smallest addressable unit capable of representing a single character. It is required to have at least 8 bits but it may (and sometimes does) have more. 8-bit-long bytes are just a "de facto" standard.
That is why many communication protocols use a concept of "octet" that consist of exactly 8 bits.
For the compiler it doesn’t matter as it is a compile time function , but it prevents from a magic number and explains what it does. sizeof is definitely the better choice and whoever sacrifices readability for a tiny flex or something.
unironically true though, the only size requirement for a char in C is that it's the smallest addressable size, which just happens to be a byte in every case and is unlikely to ever change but you still never know what the future holds
And char must be at least 8 bits. sizeof returns the size of its input in units of chars. On architectures with 10-bit chars, like some old DSPs, that means sizeof returns in multiples of 10 bits.
Look, I had a bug a few months ago where two different parts of the CI pipeline were using two different C++ compilers (clang vs gcc) and some code was breaking in only one of them because the default signedness of char was different.
Don't trust yourself to know what the spec says. size of(char) means you can't possibly be wrong. And it communicates your intent more clearly.
Except sizeof(char) is a special case of redundant because the spec says that the size of char and the size of a byte is by definition the same (regardless of what it is) so even if you have 32-bit chars then sizeof(char) must return 1 (a 32-bit int would then also return 1)
That would be a very valid reason to do it. But as an explanation for his motivations, it's kind of contradicted by the fact that he's saying "just in case."
Better use sizeof(x). If you pass a variable to sizeof it will still work. This way you're encoding the type in one place. You can easily change the type and your code will still continue to work.
sizeof always returns 1 for char because it always occupies 1 byte of memory. However, 1 byte can potentially consist of more than (but not less than) 8 bits according to C and C++ standards.
#include<assert.h>#include<uchar.h>intmain(void){const char8_t *const eight_bit_char =u8"These chars are eight bits a piece.";// must be true by definition of the standard
assert((sizeof*eight_bit_char)==1);return0;}
Don't live in the past. The future is now (C23): https://en.cppreference.com/c/header/uchar
I mean, this is true, but it's also true that sizeof(char) == 1.
What's not guaranteed is that one "byte" (= sizeof(char)) is actually one byte. char8_t could be 16 or 32 bits. Or 10 for that matter, as long as it's at least 8.
In fact, by definition char8_t is just an alias for unsigned char.
If the size matter, probably should lock the type with explicit types instead of using alias. Especially when you cross boundaries like GPU or interop.
What if I don't want to support UTF-16? What then? Sounds like you'll have a bunch of truncated characters if you don't bend to my decision as the designer.
As someone dealing with powerpc-darwin, I catch a lot of bugs in different codebases where developers just assumed bool is 1 byte, and then made structs size-sensitive. (Bool is 4 byte in ppc32 ABI.)
Bell curve. It’s a thing in statistics, left to right is value, height is amount. So the tall section in the middle is where the most people lie, and then there are very few people in the extremes.
No, there value depends on the character set. In extended ascii (dos) or ansi (win) there are still 1 byte. In utf8 where you need one bit to indicate multi-byte chars it's 2 bytes. But the charset doesn't change the size of char, which is always 1 in C.
717
u/JackReact Oct 04 '26
Welcome to the wonderful world of C#, which uses utf-16 for strings.
72
u/pyronautical Oct 05 '26
The whole, "never know what the future holds", may not necessarily be true for this, but... do I have a story for you that makes this sort of defensive programming my default now, even if the docs promise one thing.
Back in the day, I was working on a project that made some HTTP request to a payment service (In C#). It was hosted on an Azure App Service, and it was running absolutely fine.
In a code review, someone mentioned "Maybe we should force this to a specific TLS version, just incase". I looked up the docs, and given our versions, and (assumed) machine, it wasn't an issue. C# would try TLS 1.2, 1.1, then SSL3, in that specific order. You could "edit the registry" to swap the order, but when would that ever happen right? (You probably see where this is going). We were using Azure App Services which don't allow you to edit the registry anyway so what does it matter. I was in a rush, so pushed back against the code review and through we went.
Now, and this is a complete guess, but it lines up. Right at the same time, the Spectre vulnerability was released, and it forced basically everyone to "patch" their CPUs.
A week later, suddenly all payments start failing and it's impossible to figure out why until... well it seems like it's using SSL3?!? What the hell? OK let me write some diagnostics, redeploy (via a Staging slot), and check. After redeploy, it was back to TLS 1.2 as the default!?
My theory is this. Microsoft was forced to update more machines than they normally would to patch Spectre. In doing so, they had to roll customers using App Service (Remember, we can't see the underlying machine) onto really old machines or possibly even machines with fked up config, and so we ended up with a machine that had SSL3 as the default. When I redeployed, because I went via a Staging slot, it was a different machine, and so by the time I tested again, we were back to normal.
I never ever heard the end of it either. "I told you in that code review".
1.0k
u/tstanisl Oct 04 '26
Let me cite the C standard:
Middle guy if finally right
22
u/HSavinien Oct 05 '26
it's not so much a "just in case" and more a "self-documenting code". A hardcoded 1 give you a value. a sizeof(char) give you the value and tell you why it's 1.
And it's more consistant with the rest of the code. if you write
sizeof(int)for int,sizeof(long)for long, and 1 for char. it's weird and ugly.also, if you one day decide to switch char for something else, you will look everywhere you wrote char, and miss that hardcoded 1.
(in many cases, the size is used as multiplicative, so "hardcoded" will mean omitting the value entirely, rather than explicitly writing
*1, which make thing worse.)60
u/tony_saufcok Oct 04 '26
sizeof() evaluates to a constant value during compile time so what, it takes 0.0000001 seconds more during compilation? just use sizeof even if the specification guarentees it's always size 1
41
u/SeriousPlankton2000 Oct 04 '26
Use it for readability … when appropriate. If you'll never ever possibly might switch the type, don't bother.
129
u/ubalu72 Oct 04 '26
But
sizeof charis defined as 1 in the standard. C data types are defined in terms ofchar(at least their sizes are)15
u/Exatex Oct 05 '26
For the compiler it doesn’t matter as it is a compile time function , but it prevents from a magic number and explains what it does. sizeof is definitely the better choice and whoever sacrifices readability for a tiny flex or something.
13
u/Brahvim Oct 05 '26
Stop looking at it as
sizeof(char). Start looking at it assizeof(mychar_t).8
u/No-Archer-4713 Oct 05 '26
C2000 disagrees
7
u/mckenzie_keith Oct 04 '26
Best thing is to put the actual variable in there. Sizeof can accept a variable or a type.
char *buffer = 0;
size_t buffer_length = 1024;
...
buffer = malloc(buffer_length * sizeof (*buffer));
Then later if you change buffer to something else the code will still be correct.
That said, sizeof (char) will always be 1. The compiler will probably just replace it with a hard-coded 1.
7
u/goos_ Oct 05 '26
Cries in UTF-8
7
u/Ydo4ki Oct 05 '26
but sizeof returns how many chars you need to store a value, not how many bits/8... So this is literally count(1) instead of just 1
but I personally would use sizeof(char) anyway just so nobody would question the purpose of this part of the expression lmao
6
u/Adept-Painting-543 Oct 04 '26
In C though sizeof returns as a multiple of the size of char, so no matter the architecture, sizeof(char) is always 1
6
u/green_meklar Oct 05 '26
Not 'just in case', but because it expresses what you're actually doing with that number. The compiler will optimize it anyway.
11
u/frikilinux2 Oct 04 '26
Do I wanna know?
29
u/HomosexualPresence Oct 04 '26
unironically true though, the only size requirement for a char in C is that it's the smallest addressable size, which just happens to be a byte in every case and is unlikely to ever change but you still never know what the future holds
4
u/tiedyedvortex Oct 05 '26
Look, I had a bug a few months ago where two different parts of the CI pipeline were using two different C++ compilers (clang vs gcc) and some code was breaking in only one of them because the default signedness of char was different.
Don't trust yourself to know what the spec says. size of(char) means you can't possibly be wrong. And it communicates your intent more clearly.
4
u/azaleacolburn Oct 05 '26
Some people here are misunderstanding, the guy on the right is doing it for readability, not for semantics correctness
3
u/Greedy-Thought6188 Oct 05 '26
Better use sizeof(x). If you pass a variable to sizeof it will still work. This way you're encoding the type in one place. You can easily change the type and your code will still continue to work.
7
u/__christo4us Oct 04 '26
sizeofalways returns 1 forcharbecause it always occupies 1 byte of memory. However, 1 byte can potentially consist of more than (but not less than) 8 bits according to C and C++ standards.5
u/ewheck Oct 04 '26 edited Oct 05 '26
Don't live in the past. The future is now (C23): https://en.cppreference.com/c/header/uchar
2
u/pskocik Oct 04 '26
I think it's more like this https://i.postimg.cc/np0mdzz3/midwitmeme.jpg
2
u/HAL9000thebot Oct 04 '26
til that the guy in the middle is named justin case
2
u/Educational-Lemon969 Oct 05 '26
fake. the guy on right would do
sizeof(unsigned char)2
u/sirkubador Oct 07 '26
Now tell me what sizeof('A') is
2
u/Sligee Oct 04 '26
Me when my software crashes because someone entered an emoji and it overwrote something important randomly.
2
u/MatqLorens Oct 04 '26
"sizeof(char)" is much more readable for the reviewer and provides much more context than a simple "1".
Don't use magic numbers pls...
1
u/obeythelobster Oct 04 '26
In real life, the guy in the left (dumb) would never use a more complicated solution (sizeof) instead of 1
1
u/lardgsus Oct 04 '26
Me looking at the apple emoji, disagreeing.
1
u/nyibbang Oct 04 '26
CHAR_BITS / 81
u/BoBoBearDev Oct 04 '26
If the size matter, probably should lock the type with explicit types instead of using alias. Especially when you cross boundaries like GPU or interop.
1
u/Daimondz Oct 04 '26
Works way better the other way around
1
u/EuenovAyabayya Oct 05 '26
Better abstract out the sizeof to stop worrying about it.
1
u/PixelBrush6584 Oct 05 '26
stdint, my beloved ❤️
1
u/ExtraWorldliness6916 Oct 05 '26
😉
1
u/Luzzgar Oct 05 '26
Be explicit, the compiler will figure out how to make it faster.
1
u/Crimento Oct 05 '26
Give an emoji to that gentleman, good luck fitting some of them in 1 byte
1
u/AffekeNommu Oct 05 '26
I did 3 states in a SQL stored procedure with a Boolean. True, False and Null.
1
u/DogmaticParadigm87 Oct 05 '26
sizeof(char) is 1 by definition. CHAR_BIT is where the real horror lives.
1
u/JAXxXTheRipper Oct 05 '26
A UTF-8 character has a variable size between 1 and 4 bytes, so. How about them apples?
1
u/max_465 Oct 05 '26
I love those sites that have "50 misconceptions programmers have about time" ....there should be a similar one about Unicode.
1
u/afdbcreid Oct 05 '26
One
char?Maybe it's 2 bytes, if you're using C#, for example. Or 4, in Rust.
Or one char(acter)?
Sorry, it does not have a fixed size.
1
u/Vincenzo__ Oct 05 '26
Sizeof char is guaranteed to be 1. 1 byte is not necessarily 8 bits, but a char has to be 1 byte to comply with the standard
1
u/FAMICOMASTER Oct 05 '26
What if I don't want to support UTF-16? What then? Sounds like you'll have a bunch of truncated characters if you don't bend to my decision as the designer.
1
u/arjuna93 Oct 05 '26
As someone dealing with powerpc-darwin, I catch a lot of bugs in different codebases where developers just assumed bool is 1 byte, and then made structs size-sensitive. (Bool is 4 byte in ppc32 ABI.)
1
u/Selector0073 Oct 06 '26
Rust ALWAYS takes 4 bits per char
1
u/Destroyerb Oct 05 '26
I never understood what the y axis in this template is
0
u/UltimateFlyingSheep Oct 04 '26
If you're German you'll get in contact with multi byte characters pretty soon.
Umlaute like äöü are all multibyte chars.