Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guard some truncating casts with & 0xFF #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

stinos
Copy link

@stinos stinos commented Aug 11, 2016

The result of adding two unsigned chars is an int, so assigning this again
to unsigned char results in a narrowing cast. Afaik this is well-defined
by the standard but code compiled with cl with all runtime checks enabled
will trigger a breakpoint when e.g. scanline[i] + recon[i - bytewidth]
yields a number > 255. Fix this, and make it clear what's happening, by
and'ing with 0xFF (which should be discarded by any sane optimizer anyway).

@cosinekitty
Copy link
Contributor

Does an explicit cast to (unsigned char) also prevent the runtime breakpoint? That would seem clearer and would definitely avoid any unnecessary bitwise AND instructions.

@stinos
Copy link
Author

stinos commented Aug 11, 2016

No that doesn't prevent it (the truncation is still there, whether the cast is implicit or explicit). If you're concerned about casts not being optimized away I could make e.g. a function or macro narrow_cast which for msvc does the AND but for other toolsets is a no-op.

The result of adding two unsigned chars is an int, so assigning this again
to unsigned char results in a narrowing cast. Afaik this is well-defined
by the standard but code compiled with cl with all runtime checks enabled
will trigger a breakpoint when e.g. scanline[i] + recon[i - bytewidth]
yields a number > 255. Fix this, and make it clear what's happening, by
and'ing with 0xFF (which should be discarded by any sane optimizer anyway).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants