r/ProgrammerHumor • • Oct 04 '26

Meme architectureDependentChars

Post image
3.0k Upvotes

372 comments sorted by

717

u/JackReact Oct 04 '26

Welcome to the wonderful world of C#, which uses utf-16 for strings.

Console.WriteLine(sizeof(char));
> 2

262

u/v_Karas Oct 04 '26

this.

wonderd why everyone is talking about C, like there are no other languages.

96

u/Batman_AoD Oct 05 '26

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.)

3

u/KellerKindAs Oct 07 '26

C does specify the size of a char. It's exactly CHAR_BITS bits large, which is a value the compiler will know / decide at compile time

→ More replies (1)

13

u/Senior-Albatross Oct 05 '26

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. 

11

u/max_465 Oct 05 '26

The rustaceans would like a word.

13

u/Senior-Albatross Oct 05 '26

I have nothing to say to them. 

4

u/DanielMcLaury Oct 06 '26

The sizeof keyword belongs to C. If someone else appropriated it and modified it to mean something else, that's on them.

24

u/thanatica Oct 04 '26

I'm not a C# expert, but how would it represent an astral character, such as an emoji? They are above 0xFFFF.

77

u/AyrA_ch Oct 04 '26

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 also uses multibyte characters:

> "💩".length===2
< true

20

u/thanatica Oct 04 '26

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".

35

u/guyblade Oct 05 '26

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.

25

u/jmickeyd Oct 05 '26

Windows "went with it" because UCS-2, which UTF-16 is based on, predates UTF-8. When they chose to go with Unicode, it was 16 bits per character.

3

u/Numerlor Oct 05 '26

It was first and was supposed to be what utf 32 is now, didn't really work out but what's done is done

→ More replies (3)

2

u/Tiranus58 Oct 05 '26

Also emoji uses modifiers (skin tone and gender for example) and flags are just 2 characters in a trench coat.

35

u/tangerinelion Oct 04 '26

C++ has two character types, char and wchar.

sizeof(wchar) is 2 on Windows, 4 on Linux.

28

u/StaticCoder Oct 05 '26

It's wchar_t and is largely useless for the reason you mention. More recent versions have char8_t, char16_t and char32_t.

6

u/the_one2 Oct 05 '26

More recent versions have char8_t, char16_t and char32_t.

Which are also useless because they are not supported by the standard library.

8

u/StaticCoder Oct 05 '26

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.

→ More replies (1)

30

u/techy804 Oct 04 '26

As a C# user I was wondering why people act like the C-series only consists of C and C++

85

u/darkslide3000 Oct 05 '26 • Bravo

C# has about as much to do with C as JavaScript has with Java.

9

u/sisisisi1997 Oct 05 '26

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.

14

u/darkslide3000 Oct 05 '26

C# has nothing to do with C or C++ that Java doesn't have. It is entirely a Java clone.

6

u/Kovab Oct 05 '26

Nonvirtual methods, reified generics, value types, just a few examples of features from C# that don't exist in Java, but do in C++...

→ More replies (4)

31

u/AyrA_ch Oct 04 '26

Probably because the syntax more closely resembles Java than C

5

u/SuitableDragonfly Oct 04 '26

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. 

12

u/aberroco Oct 04 '26

Because most devs still think that C# is proprietary Microsoft language developed specifically and exclusively for Windows, like it's 2006.

63

u/sb8948 Oct 04 '26

No it's because C# is way closer to Java than C/C++ both in philosophy and execution.

16

u/QuaternionsRoll Oct 05 '26

It concerns me that this wasn’t the first and only answer to the question

14

u/guyblade Oct 05 '26

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.

10

u/-suspended- Oct 05 '26

Yup. C# is Microsoft Java.

3

u/kookyabird Oct 04 '26

Incorrect, they also think it’s magically cross platform when used in Unity!

→ More replies (6)

1

u/rhutyl Oct 04 '26

To me, C and C++ are just a lot more iconic (idk if "popular" is the right word bc I don't have the stats)

→ More replies (1)

3

u/klimmesil Oct 05 '26

I measure how shit a language is by the number of times I ask "but why" when I learned it. Js is still at the top, but C# is close

1

u/KellerKindAs Oct 07 '26

By that metric ARM assembly is by far the best I've learned so far xD

2

u/klimmesil Oct 07 '26

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"

1

u/earthwormjimwow Oct 05 '26

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!!

1

u/conundorum Oct 05 '26

They'd call them code units, but you probably don't want a type named cu on Windows NT.

1

u/CookIndependent6251 Oct 05 '26

In JavaScript you can't even find the size of a char. It's utf-16 as well.

1

u/crozone Oct 05 '26

Also, a char isn't necessarily an entire glyph, because UTF-16 has double-wide characters.

1

u/wishper77 Oct 05 '26

Also java if I remember correctly

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".

22

u/Justitiaria Oct 05 '26

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).

1.0k

u/tstanisl Oct 04 '26

Let me cite the C standard:

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

Middle guy if finally right

565

u/BoldFace7 Oct 04 '26

I still prefer sizeof(char) as it often provides context as to what the number is doing, even if a plain 1 works the same.

334

u/SpaceCadet87 Oct 04 '26

Yeah, guy on the right is just avoiding magic numbers in the code.

34

u/zabby39103 Oct 05 '26

If the C standard says it's 1, i'd figure it just gets optimized out by the compiler anyway?

84

u/CLOVIS-AI Oct 05 '26

sizeof is always a compiler intrinsic anyway, it's never not inlined (it's not possible to obtain this information at runtime)

34

u/Wertbon1789 Oct 05 '26

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.

→ More replies (2)

6

u/SpaceCadet87 Oct 05 '26

Should do, yeah. And if it doesn't right now, eventually it might do.

4

u/conundorum Oct 06 '26 edited Oct 06 '26

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.

→ More replies (1)
→ More replies (2)

94

u/ducon__lajoie Oct 04 '26

And someone might have #define char char16_t, right? Who the fuck knows, some people want to see the world burning.

10

u/anon_lurker69 Oct 05 '26

Yep. Its wild out there.

9

u/Kovab Oct 05 '26

I'm pretty sure redefining keywords is UB, so that's just a case of FAFO

7

u/standard_revolution Oct 05 '26

And even if it wouldn’t be: sometimes you just gotta say that something isn’t your problem

3

u/ducon__lajoie Oct 05 '26 edited Oct 05 '26

It's totally a case of FAFO, that was the joke.

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.

→ More replies (1)

50

u/RepeatRepeatR- Oct 04 '26

My opinion would be:

- Use sizeof(char) if you're actually working with characters

- Use hardcoded `1` if you're using a char as an arbitrary byte (and not actually necessarily referring to characters or text)

31

u/BoldFace7 Oct 04 '26

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).

6

u/RepeatRepeatR- Oct 04 '26

This is the way

10

u/guyblade Oct 05 '26 edited Oct 05 '26

Opinion: Always use calloc unless you've got a really, really good reason not to.

→ More replies (5)

6

u/garnet420 Oct 04 '26

A char may be bigger than 8 bits, but will always have size 1.

5

u/da_Aresinger Oct 05 '26

My opinion: if you want individual bytes use uint8_t

6

u/the_horse_gamer Oct 05 '26

bytes are not necessarily 8 bits

→ More replies (4)
→ More replies (2)

6

u/FragmentedHeap Oct 05 '26

Only applies in C, in C# sizeof(char) -> 2.

6

u/lets-start-reading Oct 05 '26

exactly. sizeof(char) may be 1, but 1 is not necessarily sizeof(char)

3

u/bowel_blaster123 Oct 05 '26 edited Oct 05 '26

What's even better is using sizeof with expressions rather than types:

char *foo_copy = malloc(foo_len * sizeof(*foo));

memcpy(foo_copy, foo, foo_len * sizeof(*foo));

Of course, it depends on the context.

1

u/two_are_stronger2 Oct 05 '26

We don't write code for the computer. We write code for people to understand the depths of our depravity, even if 'people' is us.

155

u/KitsuneFoxglove Oct 04 '26

code and society if everyone followed standards and used docs:

code at home:

63

u/locri Oct 04 '26

Today.

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.

89

u/TheSkiGeek Oct 04 '26

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.

12

u/canadajones68 Oct 05 '26

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. 

7

u/TheSkiGeek Oct 05 '26

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’.

→ More replies (1)
→ More replies (1)

14

u/aberroco Oct 04 '26

Need longer names. Some w_unicode_big_endian_char_t_ptr /s

27

u/Mojert Oct 04 '26

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

29

u/SGVsbG86KQ Oct 04 '26

No that's not how that works. Even if char would be 32 bits, sizeof(char) is still defined to be 1.

→ More replies (3)

2

u/output_broadcast Oct 04 '26

Also, not every compiler is standards-compliant.

11

u/dontthinktoohard89 Oct 05 '26

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.

→ More replies (4)
→ More replies (16)

20

u/LetUsSpeakFreely Oct 04 '26

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.

21

u/__foo__ Oct 04 '26

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.

7

u/LetUsSpeakFreely Oct 04 '26

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.

6

u/Advos_467 Oct 04 '26

Not a C user here (or any real low level programming experience), what the hell is a signed/unsigned char?

12

u/Clen23 Oct 04 '26 edited Oct 06 '26

The data is interpreted differently.

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)

8

u/YellowBunnyReddit Oct 04 '26

ASCII only goes from 0 to 127.

6

u/unknown_alt_acc Oct 04 '26

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

5

u/NotQuiteLoona Oct 04 '26 edited Oct 05 '26

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.

→ More replies (11)
→ More replies (3)

3

u/Clen23 Oct 04 '26

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
→ More replies (3)

4

u/-twind Oct 04 '26 edited Oct 05 '26

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.

4

u/backfire10z Oct 04 '26

Chars aren’t real, they’re all integers. It’s the same difference as signed/unsigned int.

→ More replies (2)

2

u/Elspeth-Nor Oct 04 '26 edited Oct 05 '26

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)

2

u/BNSable Oct 04 '26

A char is just an int, except a char will not conjure up 91, but the character assigned to the number 91 which is [ in ascii for example.

As it is an int, it can be signed or unsigned. Signed is -128 to 127, unsigned is 0 to 255.

This apparently has uses, but I am not experienced enough to explain that.

2

u/Advos_467 Oct 04 '26

Yeah that was what i assumed lol. It was mostly the uses i was wondering because with my lack of experience here, idk in what way that would be used.

→ More replies (6)
→ More replies (1)

1

u/SuitableDragonfly Oct 04 '26

char in C/++ is basically just an int.

1

u/qwertyjgly Oct 05 '26

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

#define true 1
#define false 0
typedef unsigned char bool;

int main(void){
bool a = true;
bool b = false;
}

→ More replies (7)

6

u/backfire10z Oct 04 '26

Using sizeof(char) is for readability. You understand the intent. The number 1 is a magic number that could be there for any reason.

2

u/output_broadcast Oct 04 '26

In most cases you multiply by sizeof, so you'd just leave it off altogether and there's no magic number.

1

u/Firewolf06 Oct 05 '26

sizeof(<primitive>) ≈ SIZE_OF_<CONSTANT>

theyre readability constants in effect

6

u/CptMisterNibbles Oct 04 '26

Good thing we are all writing in c, on systems that conform to the c standard.

→ More replies (4)

2

u/bwmat Oct 04 '26

Yeah, this would have been better w/ CHAR_BIT

2

u/CAtOSe Oct 04 '26

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. 

9

u/tstanisl Oct 04 '26

Some DSPs from Texas use 16/32 bit long char.

2

u/garenp Oct 04 '26

So everything really is bigger in Texas?

(I know you mean Texas Instruments / TI, but couldn't pass up the opportunity for another joke!).

→ More replies (1)

4

u/qalmakka Oct 05 '26

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

1

u/thanatica Oct 04 '26

I'm not a C guy, but if a char is 1 byte, how do you represent the one million or so characters from Unicode? Aren't those all characters in C?

1

u/tstanisl Oct 04 '26

Bytes on some machines have more than 8 bits. Moreover, unicode characters need to be encoded, usually using utf8.

→ More replies (3)

1

u/gmes78 Oct 05 '26

In C, a char is just one byte; it did correspond to a character while ASCII was being used, but, nowadays, character encodings are multi-byte.

A Unicode grapheme cluster (what you'd intuitively think of as a "character") can be composed of multiple UTF-8 bytes.

→ More replies (3)
→ More replies (3)

1

u/frank26080115 Oct 05 '26

there might be a time when the code is copied into a C-like-but-not-C language, so using sizeof(char) still has benefits

1

u/tomysshadow Oct 05 '26

Yeah, this one doesn't make much sense. Checking CHAR_BIT, on the other hand...

1

u/somedave Oct 05 '26

Yeah but if you want to port your code to C# for some reason char is now 2 byte.

1

u/mattsl Oct 05 '26

while (sizeof(char) == 1) {...

1

u/PacsfuryTemp Oct 05 '26

But 1 byte is not always 8 bits

1

u/shrodikan Oct 06 '26

I would make an argument that sizeof(char) is clearer than the magic number 1.

1

u/HRApprovedUsername Oct 04 '26

ok but what if you're not working with C?

1

u/NullOfSpace Oct 04 '26

still better to use sizeof char to make it immediately obvious what the “1” means.

→ More replies (1)
→ More replies (19)

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

9

u/Architector4 Oct 04 '26

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

10

u/AyrA_ch Oct 04 '26

Also if you ever need to modify the function to work with wide chars, then it's easier to adapt it this way.

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 char is defined as 1 in the standard. C data types are defined in terms of char (at least their sizes are)

31

u/Lonely-Discipline-55 Oct 04 '26

x = x + sizeof(char)

39

u/wittleboi420 Oct 04 '26

x = x + sizeof(char) + AI

8

u/Depnids Oct 05 '26

What

7

u/Mickanos Oct 05 '26

Look up "E = mc² + AI"

6

u/Depnids Oct 05 '26

no you do that :)

18

u/tstanisl Oct 04 '26 edited Oct 04 '26

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.

EDIT. typo

34

u/Makonede Oct 04 '26

*sizeof(char)

12

u/MegaIng Oct 04 '26

No, sizeof char is valid. sizeof is a prefix operator, not a function.

25

u/Makonede Oct 04 '26

15

u/MegaIng Oct 04 '26

Oh, never realized the prefix operator form can't be applied to types, makes sense I guess.

→ More replies (1)
→ More replies (2)

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 as sizeof(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

3

u/warpspeedSCP Oct 05 '26

Could be one! Could be three! Or maybe its four. Eeeeheheheeee!

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?

6

u/DOOManiac Oct 04 '26

Yes. Multi-byte characters.

There you go, all done.

22

u/frikilinux2 Oct 04 '26

But those don't have the c type char

→ More replies (2)

1

u/Still_Bit_7527 Oct 05 '26

Aren't they supported natively in c++? Wtf.

→ More replies (12)

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

50

u/lotanis Oct 04 '26

Yes, but the smallest addressable size is what dictates the base size for sizeof.

The C standard in fact says this about sizeof:

When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. 

2

u/FUCKING_HATE_REDDIT Oct 04 '26

What about a system that enforces addresses to be multiples of 2, or 4?

8

u/dontthinktoohard89 Oct 05 '26

In short, the standard mandates that a char is exactly 1 byte. It does not dictate how wide a “byte” actually is.

→ More replies (2)

1

u/MateoConLechuga Oct 05 '26

That doesn't mean 1 byte.

9

u/SAI_Peregrinus Oct 04 '26

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.

1

u/StaticCoder Oct 05 '26

A byte is often defined as the smallest addressable size. An octet must be 8 bits.

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.

3

u/DanielMcLaury Oct 06 '26

Hey everyone, look at this guy! He doesn't even know that the C standard doesn't specify the signedness of char!

2

u/GOKOP Oct 05 '26

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)

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

1

u/DanielMcLaury Oct 06 '26

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."

1

u/azaleacolburn Oct 07 '26

"just in case" someone doesn't understand what I'm doing

→ More replies (1)

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

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.

5

u/ewheck Oct 04 '26 edited Oct 05 '26
#include <assert.h>
#include <uchar.h>

int main(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); 

    return 0;
}

Don't live in the past. The future is now (C23): https://en.cppreference.com/c/header/uchar

4

u/mad_cheese_hattwe Oct 04 '26

uint_8 but same diff

3

u/dontthinktoohard89 Oct 05 '26

The size of a pointer is not guaranteed to be 1 lmao

→ More replies (1)

1

u/StaticCoder Oct 05 '26

8 bit pointers? Sounds like the past.

1

u/DanielMcLaury Oct 06 '26

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.

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 / 8

2

u/dontthinktoohard89 Oct 05 '26

This is wrong as a substitute for sizeof(char). The former is guaranteed to be 1, this is guaranteed to be at least 1.

1

u/nyibbang Oct 05 '26

I know, it was a joke. It seems like some people expect sizeof(char) to be something other than 1, so there, here is a solution for them.

1

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/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

2

u/CalvesReignSupreme Oct 05 '26

Distribution. Basically this shows all people that exist (100%), meaning there is no unit of measurement anyway. So no need for a labeled axis

→ More replies (8)

1

u/Atompunk78 Oct 05 '26

The Y axis at a given point X represents the proportion of people at X, eg the proportion of people with that iq

→ More replies (2)

1

u/Takamasa1 Oct 05 '26

IQ distribution. It's an artificially normal distribution as a benchmark since it is defining an abstract unit.

1

u/eddiekoski Oct 05 '26

Its how many people think that way *

1

u/HolyElephantMG Oct 06 '26

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.

→ More replies (4)

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.

3

u/Elspeth-Nor Oct 04 '26

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.