Bug 44179 - warn about sizeof(char) and sizeof('x')
Summary: warn about sizeof(char) and sizeof('x')
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: unknown
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
Keywords: diagnostic
Depends on:
Blocks: new-warning, new_warning
  Show dependency treegraph
Reported: 2010-05-17 22:08 UTC by Zack Weinberg
Modified: 2023-12-16 15:26 UTC (History)
4 users (show)

See Also:
Known to work:
Known to fail:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description Zack Weinberg 2010-05-17 22:08:14 UTC
sizeof(char) is defined to be 1, and is therefore almost always unnecessary.  It would be nice if the C and C++ front ends could complain about it.
Comment 1 Andrew Pinski 2010-05-17 22:10:40 UTC
I can see a case involving templates or macros where the warning does not make sense and involving the new C1x/C++0x static_assert too.
Comment 2 Zack Weinberg 2010-05-17 23:59:10 UTC
So it has to be a little smarter than the obvious, so what else is new.
Comment 3 Zack Weinberg 2023-12-15 14:09:16 UTC
It's come to my attention that people fairly often write `sizeof('x')` (or some other character constant), _expecting_ it to evaluate as `sizeof(char)`.  But this is only true in C++. In C, `sizeof('x')` evaluates as `sizeof(int)`.

See http://codesearch.debian.net/search?q=filetype%3Ac+%5Cbsizeof%5Cs*%5C%28%5Cs*%27&literal=0 for many examples.

It's probably more important to warn about this than about `sizeof(char)` itself.
Comment 4 Harald van Dijk 2023-12-16 15:17:21 UTC
(In reply to Zack Weinberg from comment #3)
> See
> http://codesearch.debian.net/
> search?q=filetype%3Ac+%5Cbsizeof%5Cs*%5C%28%5Cs*%27&literal=0 for many
> examples.

There is a lot in there where a warning would be useful, but also a lot in there where a warning would not be useful because the only reason the code is doing sizeof('x') is because it's making sure that it actually is sizeof(int), to check that it's not being compiled with a C++ compiler, or a C compiler that picked up some C++isms by mistake. If GCC decides to warn about that, it is not obvious how the code should be rewritten to silence the warning, but still have the desired effect. In other places, redundant parentheses can be added to indicate that a use is intentional ("if (a = b)" warns, "if ((a = b))" shuts up the compiler), but sizeof('x') already has redundant parentheses. Would users then be suggested to write sizeof(('x'))?
Comment 5 Alexander Monakov 2023-12-16 15:26:09 UTC
Warning when sizeof 'x' appears as a term in an addition/subtraction would catch the misuses while leaving instances like assert(sizeof 'x' == 4) be.