Path: csiph.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: Safety of casting from 'long' to 'int'
Date: Thu, 30 Apr 2026 00:56:08 -0700
Organization: A noiseless patient Spider
Lines: 23
Message-ID: <86pl3gzxt3.fsf@linuxsc.com>
References: <10su8cn$am9i$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Date: Thu, 30 Apr 2026 07:56:09 +0000 (UTC)
Injection-Info: dont-email.me; posting-host="7ff432f926fb921b7df3a70694682c9f"; logging-data="540096"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19VI1P+A7Xc7cKu06GBylk/KpQmJiuXY1E="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:xImuzm8YCisVagh1ZipqoFmhtsg= sha1:q57hUWjm0ViLe48ttGpGuHiFbi0=
Xref: csiph.com comp.lang.c:398124
kalevi@kolttonen.fi (Kalevi Kolttonen) writes:
> Hello!
>
> A simple question and yes, I know I could ask AI bots
> but the problem is that I cannot always trust their
> responses.
>
> Is it always safe and not undefined behavior to do:
>
> int i;
> long l;
> i = (int)l;
>
> as long as you have first veried that 'l' is within
> the range between INT_MIN and INT_MAX? Thanks.
Assuming the variable 'l' has been given a value, the assignment
to 'i' is always defined (and by the way the cast is not needed),
and never undefined behavior. If the value in 'l' lies within the
range of int the value is unchanged. If the value in 'l' lies
outside the range of int, the result is implementation-defined or
an implementation-defined signal is raised.