6

I've got a question about using suffix for numbers in C.

Example:

long long c;

The variable c is of long long type. To initiate its value, I do (usually)

c = 12;

When done like that, the compiler recognizes c as a long long type.

Then, if I do

printf("%d",sizeof(c));

the result is 8 - which of course is 64 bit. So the compiler remembers that c is of long long type.

But I've seen some examples where I need to force the type to be long long, by doing

c = 12LL

Why is that?

2 Answers2

6

You're declaring the variable c as a long long, so it's a long long int. The type of the variable is not dependent on its value; rather, the range of possible values for c is dependent on the type of c.

On the other hand: For an integer constant/literal, the type is determined by its value and suffix (if any). 12 has no prefix, so it's a decimal constant. And it has no suffix, meaning it has a type of int, since 12 is guaranteed to be in the long range of it. 12LL has no prefix, so it's also a decimal constant. It has a suffix of LL, meaning it has a type of long long int. It's safe to assign 12 to the variable c, because an int can safely be converted to a long long int.

Hope that helps.

Chris Tang
  • 567
  • 7
  • 18
Frank H.
  • 1
  • 1
  • 11
  • 25
  • Ah. I would like to say "ah, of course!", but I'll settle for "Ah" :-) –  Aug 13 '14 at 16:28
  • 1
    "12 has no prefix, so it's a decimal constant." is incomplete. `0` is an unsigned octal constant. `012345` is also an unsigned octal constant. On a 32-bit machine `4000000000` is an unsigned decimal. This answer's discussion on suffixes is good, but constants with/without prefixes need calcification. – chux - Reinstate Monica Aug 13 '14 at 16:42
2
long long c;
c = 12;

c is of type long long but 12 is of type int. When 12 is assigned to long long object c it is first converted to long long and then assigned to c.

c = 12LL;

does exactly the same assignment, only there is no need to implicitly convert it first. Both assignments are equivalent and no sane compiler will make a difference.

Note that some coding guides, from example MISRA (for automotive embedded code) requires constants assigned to unsigned types to be suffixed with U:

Example, in C both assignments (here unsigned int x;) are equivalent:

 x = 0;   /* non-MISRA compliant */
 x = 0U;

but MISRA requires the second form (MISRA-C:2004, rule 10.6).

ouah
  • 142,963
  • 15
  • 272
  • 331