implicit long int -> int ?

A

Alexander Korovyev

Is there an expression where an int may be used while a long int may
not?
The standard ('99) says:
"The following may be used in an expression wherever an int or
unsigned int may be used:
- An object or expression with an integer type whose integer
conversion rank is less than the rank of int and unsigned int.
- A bit-field of type _Bool, int, signed int, or unsigned int."
Does there exist an example of the sort I described or other rules
apply which imply non-existence of this example? Thanks!
 
J

Jeremy Yallop

Alexander said:
Is there an expression where an int may be used while a long int may
not?

Yes. It's not valid to pass a long int as an argument to an
unprototyped or variadic function expecting an int:

#include <stdio.h>
printf("%d", 1); /* valid */
printf("%d", 1L); /* invalid */

int abs();
abs(1); /* valid */
abs(1L); /* invalid */

Also, the usual arithemtic conversions may lead to an overflow in
certain circumstances if a long int is substituted for an int.
Consider a machine where int and long are the same width, and INT_MAX
is equal to UINT_MAX. Then in the expression

UINT_MAX + 1

the second operand is converted to unsigned int, which is also the
type of the whole expression; the value is 0. If the second operand
is a long, however:

UINT_MAX + 1L

the first operand is converted to long, and the expression results in
an overflow, which is undefined behaviour.

There are also examples involving sizeof:

int x[sizeof(int)] = {0};
x[(sizeof 1) - 1];
x[(sizeof 1L) - 1];

The last statement has undefined behaviour on machines where long is
larger than int.

Jeremy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top