Re: Undesired automatic cast, workarounds?

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

 



Hi Pablo,

> how do I then tell the compiler to keep the type?

I'm not really sure what you are trying to do.

Do you want to make sure that integral promotion is explicit in the code?

I, personally, like that approach... but I like B&D languages like Ada, so
I'm atypical.  That shouldn't impose any additional performance penalty.

Are you trying to eke every little bit of performance out of the operation?

You may want to read the book "Hacker's Delight" by Henry S. Warren.

It's not about "hacker" in the bad sense as used by the media, it's about
"hacker" in the good sense as used by programmers -- bit twiddling and
blazing performance lore all collected in one enjoyable book.

Also be very careful about alignment, since an array of bytes (char) may not
have the right kind of alignment to be treated as an array of words (int).

Also, assuming that int is 4-bytes may make for porting issues.  You may
want to use int32_t from C99's stdint.h.

I'm not sure if representing the pixels in a union would negatively impact
performance, but it could avoid alignment problems.

struct RGB
{
  byte mRed;
  byte mGreen;
  byte mBlue;
  byte mFallow; // mPad? mGarbage? mAlpha? mZero? m255?
}

union Pixel
{
  struct RGB mRGB;
  int32_t mPixel; // Be mindful of endian-ness.
};

Are you worried about promotion / slicing performance impact?

Profile the code.

Look at the assembly output of the routine compiled with -O2 or -O3.
Sometimes you can tweak the routine (usually at the "cost" of making the
routine a bit more harder to maintain) to allow the optimizer a better job
to optimize.

Do not bother to look at the assembly output of the routine compiled with
-O0 (unoptimized).

> warning: conversion to 'lti::ubyte' from 'int' may alter its value

// Assuming unsigned char as byte.  Change accordingly.
typedef unsigned char byte;
#define BYTE_MIN 0
#define BYTE_MAX 255

bool ParanoiaIntToByte(int c)
{
  return c >= BYTE_MIN && c <= BYTE_MAX;
}

int c = some_int_fn();
assert(ParanoiaIntToByte(c));
byte b0 = c; // implicit slice.  Warning?
byte b1 = byte(c); // explicit slice.  Warning?

Do you need to worry about saturation?  Such that when c>255 it ceiling's to
255, or when c<0 it floor's to 0?

HTH,
--Eljay


[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