Re: Integral conversions in C/C++

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi everyone,

-->8---

#include <stdint.h>

// ...

int64_t a;
uint32_t b = 8;

a = -(b * 2u);

--->8---

In the context of the question, it is a 32-bit int platform.  The binary and
unary operators on the provided types yield the resulting type.

uint32_t * uint32_t ==> uint32_t
- uint32_t          ==> uint32_t
int64_t = uint32_t  ==> int64_t

As I understand the discussion, the concern was that the negation of a
uint32_t was undesirably an uint32_t.  Which is what the standard says it
must do on this kind of platform.

It appears that the desired behavior is...
a = -(int64_t)(b * 2u);
...but without having to explicitly specify the conversion.  Alas,
explicitly specifying the conversion is needed.

Here's a bit of code that I <sarcasm>love</sarcasm>:

--------------------------------------------------
#include <iostream>
#include <typeinfo>
// Assuming a 32-bit int platform, and short is 16-bit.
typedef unsigned short int uint16_t;
typedef signed int int32_t;
int main()
{
  uint16_t s = 0xFFFFU;
  std::cout << (s * s) << std::endl;
  std::cout << typeid(uint16_t).name() << std::endl;
  std::cout << typeid(int32_t).name() << std::endl;
  std::cout << typeid(s).name() << std::endl;
  std::cout << typeid(s * s).name() << std::endl;
}
--------------------------------------------------

uint16_t * uint16_t ==> int32_t

Yep, multiplying two uint16_t results in a int32_t, not a uint32_t.
Surprise!

There are a few sharp edges to C and C++.

This forum can help diagnose when someone hits one of those sharp edges.

This forum cannot change the standard.  This is not a standards forum.

If anyone wants to change C, or C++, the result is something that may be
similar to C or C++, but is not C or C++.

Anyone can use FSF's GCC to create their own language.

I've tried, and it turns out that writing my own perfect language is quite a
bit more work than I thought going into the project.  Now my Aho dragon book
is just collecting dust.  But on the bright side, D Programming Language
implements 95%+ of what I would have liked in my own homebrew language, and
has a GCC implementation (gdc).

Sincerely,
--Eljay

PS:  I once had a chance to talk to Bjarne Stroustrup, with my litany of
complaints with C++.  He stopped me short, and replied (paraphrased) "If you
do not like C++, you are free to create your own language.  I did."  In
hindsight, I'm sure he's heard more than his fair share of complaints about
C++ (my apologies Bjarne!), I appreciate his response, and I'm grateful he
stopped me before I continued to embarrass myself.


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux