0

In the source code, I have a negative int literal. When I parse the source code through libclang, the integer_leteral functions clang_Cursor_Evaluate and clang_EvalResult_getAsInt return a positive value for this.

For example, I had int a = -555 in the source code. If you get this integer_value and call the clang_Cursor_Evaluate and clang_EvalResult_getAsInt functions for it, the latter will simply return 555. Why is this happening?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jurddox
  • 21
  • 1
  • 4
  • 2
    There are no negative integer literals in C (and I believe C++). There are positive literals (or zero) and unary `-` operator. – Eugene Sh. Mar 06 '23 at 20:52
  • 1
    related/dupe/fun read: https://stackoverflow.com/questions/45469214/why-does-the-most-negative-int-value-cause-an-error-about-ambiguous-function-ove/45469321#45469321 – NathanOliver Mar 06 '23 at 20:52

1 Answers1

4

There are no negative integer literals in C and C++. When you have something like -555 that's an integer literal 555 and a unary minus operator. A decimal integer has a signed integral type that won't be promoted, so that works out to the expected type and value.

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • is there a rationale behind this choice of representation? – helix Jun 10 '23 at 19:00
  • @helix As far as I can tell it has always been like that in C++, C and also C's predecessors. I guess it is probably because forming of preprocessor tokens would otherwise get more complex, e.g. `-1` could be a single literal token or a `-` token followed by a literal token depending on the token preceding it, e.g. `1 -1` vs `= -1`. – user17732522 Jun 10 '23 at 20:14