-1

I've recently met code like this

struct tcpheader {
 unsigned char      tcph_reserved:4, tcph_offset:4;
 ....

Its obvious what the : sort of do, but why have I never met this officially? I can't find where the formal definition of the : operator is. I've searched partitioning, splitting, and dividing of variable declaration to no avail.

Anyone have some information on the : operator?

ani627
  • 5,578
  • 8
  • 39
  • 45
Helical
  • 125
  • 9

4 Answers4

6

It's not an "operator", it's a way of declaring something called bit fields.

It's only valid inside struct and union declarations, and basically lets you tell the compiler how many bits you want the field to use.

So your example specifies four bits for each field, probably expecting both of the fields to be packed into the same 8-bit byte.

Note that the order and layout of bits when using bit fields is unspecified and up to the compiler, making them very unportable.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

: is not an operator, it is called the colon punctuator and is used to specify the width of a bit-field.

http://en.wikipedia.org/wiki/Bit_field

ouah
  • 142,963
  • 15
  • 272
  • 331
1

This is : not an operator. This is Bitfields. Some web searching will yield more info about them than you could ever want. But basically the number after the colon describes how many bits that field uses.

In your code-

struct tcpheader {
 unsigned char      tcph_reserved:4, tcph_offset:4;

Normally unsigned char have 8-bit's. tcph_reserved:4 means you are allocating 4 bits to tcph_reserved.

Bit fields are valid only in Structures and Unions

Sathish
  • 3,740
  • 1
  • 17
  • 28
  • How was I supposed to know its called Bitfields??, I was looking for variable split, partition, divide. – Helical Sep 02 '14 at 13:51
  • @user3167049 This answer is based on your question! If you have something like this in structure `unsigned char tcph_reserved:4;` blindly you can say it is bit field! – Sathish Sep 02 '14 at 13:58
0

I wiil not add anything to the earlier answers that well explained the fact that : is used to indicate bit-field members in struct declarations.

On the other hand, in C we have the ternary operator ? : which works in this way, for example:

    int condition = 3 > 4;
    char result1 = 'x', result2 = 'A';
    char x = (condition)? result1 : result2; 
  • The ternary operator evaluates a condition.
  • If the condition is true (non-zero value), then the expression result1 is evaluated.
  • If the condition is false (zero value), then the expression result2 is evaluated.

In other words, it's a short-hand for an if() sentence, with the advantage that can be used in expressions.

As you can see, the character : is part of the ternary operator ?:, but it's not an operator by its own, since it goes joint to the character ?.

pablo1977
  • 4,281
  • 1
  • 15
  • 41