3

Suppose we want to return a long integer by a function. How to do it? Is it valid?

long int function()
{
  long int b;
  b=1000000000;
  return b;
} 
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
Vasu Dev Garg
  • 121
  • 1
  • 15

4 Answers4

12

Yes, it is valid.

As long as you're retuning a proper long int value (which we can see, you're doing#) and catching that into another long int (you need to take care), it should be fine.


#) As per the C11 standard, LONG_MAX is +2147483647 and 1000000000 is less than that. Chapter §5.2.4.2.1, for reference.

Natasha Dutta
  • 3,242
  • 21
  • 23
6

Can long int be returned by a function in c?

Can long int be returned by a function in c?

         

Persixty
  • 8,165
  • 2
  • 13
  • 35
  • Apologies to the three detractors who clearly think I'm lowering the tone. But I and two others thought it was funny. So I'm saying the jury is still out on this one. – Persixty May 22 '15 at 09:30
  • This answer continues to divide opinion but at least those in favour now out number those against. – Persixty Jun 09 '15 at 16:48
2

The C standard stipulates a minimum size of 32 bits for a long int, stored in such a way as to guarantee that values in the range [−2147483647, +2147483647] can be represented. (Note that a 2s compliment representation gives you −2147483648). So the assignment of 1,000,000,000 to a long int is always defined.

Returning a value copy of a long int is well-defined too.

Note that if you hadn't initialised b (i.e. if you had omitted the statement b=1000000000;), then the behaviour of your program would have been undefined.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I don't quite see what the value limits of a long have to do with the question. – Lundin May 20 '15 at 12:54
  • How could you? I upvoted your answer :-) Seriously, it would have been very relevant had the OP, say had wanted to assign 10,000,000,000 to the `long int`. That's not always well-defined. – Bathsheba May 20 '15 at 12:55
  • The type of the integer literal itself is the smallest possible that can fit the number, for the given system. But it is never smaller than `int`. This is well-defined in 6.4.4.1. In case of 10 billion, the compiler would likely pick type `long long int`. If you then show that into a long, the following applies (6.3.1.3) `"Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised."`. So something implementation-defined is guaranteed to happen. – Lundin May 20 '15 at 13:04
2

A function can return pretty much any type:

6.9.1

The return type of a function shall be void or a complete object type other than array type.

And that's it.

Lundin
  • 195,001
  • 40
  • 254
  • 396