cppreference.com

Union declaration.

A union is a special class type that can hold only one of its non-static data members at a time.

[ edit ] Syntax

The class specifier for a union declaration is similar to class or struct declaration:

A union can have member functions (including constructors and destructors), but not virtual functions.

A union cannot have base classes and cannot be used as a base class.

A union cannot have non-static data members of reference types.

Just like in struct declaration, the default member access in a union is public .

[ edit ] Explanation

The union is at least as big as necessary to hold its largest data member, but is usually not larger. The other data members are intended to be allocated in the same bytes as part of that largest member. The details of that allocation are implementation-defined, except that all non-static data members have the same address. It is undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.

Possible output:

Each member is allocated as if it is the only member of the class.

If two union members are standard-layout types, it's well-defined to examine their common subsequence on any compiler.

[ edit ] Member lifetime

The lifetime of a union member begins when the member is made active. If another member was active previously, its lifetime ends.

When active member of a union is switched by an assignment expression of the form E1 = E2 that uses either the built-in assignment operator or a trivial assignment operator, for each union member X that appears in the member access and array subscript subexpressions of E1 that is not a class with non-trivial or deleted default constructors, if modification of X would have undefined behavior under type aliasing rules, an object of the type of X is implicitly created in the nominated storage; no initialization is performed and the beginning of its lifetime is sequenced after the value computation of the left and right operands and before the assignment.

Trivial move constructor, move assignment operator, (since C++11) copy constructor and copy assignment operator of union types copy object representations. If the source and the destination are not the same object, these special member functions start lifetime of every object (except for objects that are neither subobjects of the destination nor of implicit-lifetime type ) nested in the destination corresponding to the one nested in the source before the copy is performed. Otherwise, they do nothing. Two union objects have the same corresponding active member (if any) after construction or assignment via trivial special functions.

[ edit ] Anonymous unions

An anonymous union is an unnamed union definition that does not simultaneously define any variables (including objects of the union type, references, or pointers to the union).

Anonymous unions have further restrictions: they cannot have member functions, cannot have static data members, and all their data members must be public. The only declarations allowed are non-static data members and static_assert declarations (since C++11) .

Members of an anonymous union are injected in the enclosing scope (and must not conflict with other names declared there).

Namespace-scope anonymous unions must be declared static unless they appear in an unnamed namespace.

[ edit ] Union-like classes

A union-like class is either a union, or a (non-union) class that has at least one anonymous union as a member. A union-like class has a set of variant members :

  • the non-static data members of its member anonymous unions;
  • in addition, if the union-like class is a union, its non-static data members that are not anonymous unions.

Union-like classes can be used to implement tagged union .

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • Pages with unreviewed CWG DR marker
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 26 November 2023, at 23:36.
  • This page has been accessed 1,172,514 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

The GNU C Reference Manual

Table of contents, 1.1 identifiers, 1.2 keywords, 1.3.1 integer constants, 1.3.2 character constants, 1.3.3 real number constants, 1.3.4 string constants, 1.4 operators, 1.5 separators, 1.6 white space, 2.1.1 integer types, 2.1.2 real number types, 2.1.3.1 standard complex number types, 2.1.3.2 gnu extensions for complex number types, 2.2.1 defining enumerations, 2.2.2 declaring enumerations, 2.3.1 defining unions, 2.3.2.1 declaring union variables at definition, 2.3.2.2 declaring union variables after definition, 2.3.2.3 initializing union members, 2.3.3 accessing union members, 2.3.4 size of unions, 2.4.1 defining structures, 2.4.2.1 declaring structure variables at definition, 2.4.2.2 declaring structure variables after definition, 2.4.2.3 initializing structure members, 2.4.3 accessing structure members, 2.4.4 bit fields, 2.4.5 size of structures, 2.5.1 declaring arrays, 2.5.2 initializing arrays, 2.5.3 accessing array elements, 2.5.4 multidimensional arrays, 2.5.5 arrays as strings, 2.5.6 arrays of unions, 2.5.7 arrays of structures, 2.6.1 declaring pointers, 2.6.2 initializing pointers, 2.6.3 pointers to unions, 2.6.4 pointers to structures, 2.7 incomplete types, 2.8 type qualifiers, 2.9 storage class specifiers, 2.10 renaming types, 3.1 expressions, 3.2 assignment operators, 3.3 incrementing and decrementing, 3.4 arithmetic operators, 3.5 complex conjugation, 3.6 comparison operators, 3.7 logical operators, 3.8 bit shifting, 3.9 bitwise logical operators, 3.10 pointer operators, 3.11 the sizeof operator, 3.12 type casts, 3.13 array subscripts, 3.14 function calls as expressions, 3.15 the comma operator, 3.16 member access expressions, 3.17 conditional expressions, 3.18 statements and declarations in expressions, 3.19 operator precedence, 3.20.1 side effects, 3.20.2 sequence points, 3.20.3 sequence points constrain expressions, 3.20.4 sequence points and signal delivery, 4.2 expression statements, 4.3 the if statement, 4.4 the switch statement, 4.5 the while statement, 4.6 the do statement, 4.7 the for statement, 4.9 the null statement, 4.10 the goto statement, 4.11 the break statement, 4.12 the continue statement, 4.13 the return statement, 4.14 the typedef statement, 5.1 function declarations, 5.2 function definitions, 5.3 calling functions, 5.4 function parameters, 5.5 variable length parameter lists, 5.6 calling functions through function pointers, 5.7 the main function, 5.8 recursive functions, 5.9 static functions, 5.10 nested functions, 6.1 program structure, 7.1 hello.c, 7.2 system.h, a.1 basics of integer overflow, a.2 examples of code assuming wraparound overflow, a.3 optimizations that break wraparound arithmetic, a.4 practical advice for signed overflow issues, a.5 signed integer division and integer overflow, gnu free documentation license.

Next: Preface , Up: (dir)   [ Contents ][ Index ]

This is the GNU C reference manual.

Next: Lexical Elements , Previous: Top , Up: Top   [ Contents ][ Index ]

This is a reference manual for the C programming language as implemented by the GNU Compiler Collection (GCC). Specifically, this manual aims to document:

  • The 1989 ANSI C standard, commonly known as “C89”
  • The 1999 ISO C standard, commonly known as “C99”, to the extent that C99 is implemented by GCC
  • The current state of GNU extensions to standard C

This manual describes C89 as its baseline. C99 features and GNU extensions are explicitly labeled as such.

By default, GCC will compile code as C89 plus GNU-specific extensions. Much of C99 is supported; once full support is available, the default compilation dialect will be C99 plus GNU-specific extensions. (Some of the GNU extensions to C89 ended up, sometimes slightly modified, as standard language features in C99.)

The C language includes a set of preprocessor directives, which are used for things such as macro text replacement, conditional compilation, and file inclusion. Although normally described in a C language manual, the GNU C preprocessor has been thoroughly documented in The C Preprocessor , a separate manual which covers preprocessing for C, C++, and Objective-C programs, so it is not included here.

Thanks to everyone who has helped with editing, proofreading, ideas, typesetting, and administrivia, including: Diego Andres Alvarez Marin, Nelson H. F. Beebe, Karl Berry, Robert Chassell, Hanfeng Chen, Mark de Volld, Antonio Diaz Diaz, dine, Andreas Foerster, Denver Gingerich, Lisa Goldstein, Robert Hansen, Jean-Christophe Helary, Mogens Hetsholm, Teddy Hogeborn, Joe Humphries, J. Wren Hunt, Dutch Ingraham, Adam Johansen, Vladimir Kadlec, Benjamin Kagia, Dright Kayorent, Sugun Kedambadi, Felix Lee, Bjorn Liencres, Steve Morningthunder, Aljosha Papsch, Matthew Plant, Jonathan Sisti, Richard Stallman, J. Otto Tennant, Ole Tetlie, Keith Thompson, T.F. Torrey, James Youngman, and Steve Zachar. Trevis Rothwell serves as project maintainer and, along with James Youngman, wrote the bulk of the text.

Some example programs are based on algorithms in Donald Knuth’s The Art of Computer Programming .

Please send bug reports and suggestions to [email protected] .

Next: Data Types , Previous: Preface , Up: Top   [ Contents ][ Index ]

1 Lexical Elements

This chapter describes the lexical elements that make up C source code after preprocessing. These elements are called tokens . There are five types of tokens: keywords, identifiers, constants, operators, and separators. White space, sometimes required to separate tokens, is also described in this chapter.

Next: Keywords , Up: Lexical Elements   [ Contents ][ Index ]

Identifiers are sequences of characters used for naming variables, functions, new data types, and preprocessor macros. You can include letters, decimal digits, and the underscore character ‘ _ ’ in identifiers.

The first character of an identifier cannot be a digit.

Lowercase letters and uppercase letters are distinct, such that foo and FOO are two different identifiers.

When using GNU extensions, you can also include the dollar sign character ‘ $ ’ in identifiers.

Next: Constants , Previous: Identifiers , Up: Lexical Elements   [ Contents ][ Index ]

Keywords are special identifiers reserved for use as part of the programming language itself. You cannot use them for any other purpose.

Here is a list of keywords recognized by ANSI C89:

ISO C99 adds the following keywords:

and GNU extensions add these keywords:

In both ISO C99 and C89 with GNU extensions, the following is also recognized as a keyword:

Next: Operators , Previous: Keywords , Up: Lexical Elements   [ Contents ][ Index ]

1.3 Constants

A constant is a literal numeric or character value, such as 5 or 'm' . All constants are of a particular data type; you can use type casting to explicitly specify the type of a constant, or let the compiler use the default type based on the value of the constant.

Next: Character Constants , Up: Constants   [ Contents ][ Index ]

An integer constant is a sequence of digits, with an optional prefix to denote a number base.

If the sequence of digits is preceded by 0x or 0X (zero x or zero X), then the constant is considered to be hexadecimal (base 16). Hexadecimal values may use the digits from 0 to 9, as well as the letters a to f and A to F . Here are some examples:

If the first digit is 0 (zero), and the next character is not ‘ x ’ or ‘ X ’, then the constant is considered to be octal (base 8). Octal values may only use the digits from 0 to 7; 8 and 9 are not allowed. Here are some examples:

In all other cases, the sequence of digits is assumed to be decimal (base 10). Decimal values may use the digits from 0 to 9. Here are some examples:

There are various integer data types, for short integers, long integers, signed integers, and unsigned integers. You can force an integer constant to be of a long and/or unsigned integer type by appending a sequence of one or more letters to the end of the constant:

Unsigned integer type.

Long integer type.

For example, 45U is an unsigned int constant. You can also combine letters: 45UL is an unsigned long int constant. (The letters may be used in any order.)

Both ISO C99 and GNU C extensions add the integer types long long int and unsigned long long int . You can use two ‘ L ’s to get a long long int constant; add a ‘ U ’ to that and you have an unsigned long long int constant. For example: 45ULL .

Next: Real Number Constants , Previous: Integer Constants , Up: Constants   [ Contents ][ Index ]

A character constant is usually a single character enclosed within single quotation marks, such as 'Q' . A character constant is of type int by default.

Some characters, such as the single quotation mark character itself, cannot be represented using only one character. To represent such characters, there are several “escape sequences” that you can use:

Backslash character.

Question mark character.

Single quotation mark.

Double quotation mark.

Audible alert.

Backspace character.

<ESC> character. (This is a GNU extension.)

Newline character.

Carriage return.

Horizontal tab.

Vertical tab.

Octal number.

Hexadecimal number.

To use any of these escape sequences, enclose the sequence in single quotes, and treat it as if it were any other character. For example, the letter m is 'm' and the newline character is '\n' .

The octal number escape sequence is the backslash character followed by one, two, or three octal digits (0 to 7). For example, 101 is the octal equivalent of 65, which is the ASCII character 'A' . Thus, the character constant '\101' is the same as the character constant 'A' .

The hexadecimal escape sequence is the backslash character, followed by x and an unlimited number of hexadecimal digits (0 to 9, and a to f or A to F ).

While the length of possible hexadecimal digit strings is unlimited, the number of character constants in any given character set is not. (The much-used extended ASCII character set, for example, has only 256 characters in it.) If you try to use a hexadecimal value that is outside the range of characters, you will get a compile-time error.

Next: String Constants , Previous: Character Constants , Up: Constants   [ Contents ][ Index ]

A real number constant is a value that represents a fractional (floating point) number. It consists of a sequence of digits which represents the integer (or “whole”) part of the number, a decimal point, and a sequence of digits which represents the fractional part.

Either the integer part or the fractional part may be omitted, but not both. Here are some examples:

(In the third assignment statement, the integer constant 4 is automatically converted from an integer value to a double value.)

Real number constants can also be followed by e or E , and an integer exponent. The exponent can be either positive or negative.

You can append a letter to the end of a real number constant to cause it to be of a particular type. If you append the letter F (or f) to a real number constant, then its type is float . If you append the letter L (or l), then its type is long double . If you do not append any letters, then its type is double .

Previous: Real Number Constants , Up: Constants   [ Contents ][ Index ]

A string constant is a sequence of zero or more characters, digits, and escape sequences enclosed within double quotation marks. A string constant is of type “array of characters”. All string constants contain a null termination character ( \0 ) as their last character. Strings are stored as arrays of characters, with no inherent size attribute. The null termination character lets string-processing functions know where the string ends.

Adjacent string constants are concatenated (combined) into one string, with the null termination character added to the end of the final concatenated string.

A string cannot contain double quotation marks, as double quotation marks are used to enclose the string. To include the double quotation mark character in a string, use the \" escape sequence. You can use any of the escape sequences that can be used as character constants in strings. Here are some example of string constants:

If a string is too long to fit on one line, you can use a backslash \ to break it up onto separate lines.

Adjacent strings are automatically concatenated, so you can also have string constants span multiple lines by writing them as separate, adjacent, strings. For example:

is the same as

To insert a newline character into the string, so that when the string is printed it will be printed on two different lines, you can use the newline escape sequence ‘ \n ’.

Next: Separators , Previous: Constants , Up: Lexical Elements   [ Contents ][ Index ]

An operator is a special token that performs an operation, such as addition or subtraction, on either one, two, or three operands. Full coverage of operators can be found in a later chapter. See Expressions and Operators .

Next: White Space , Previous: Operators , Up: Lexical Elements   [ Contents ][ Index ]

A separator separates tokens. White space (see next section) is a separator, but it is not a token. The other separators are all single-character tokens themselves:

Previous: Separators , Up: Lexical Elements   [ Contents ][ Index ]

White space is the collective term used for several characters: the space character, the tab character, the newline character, the vertical tab character, and the form-feed character. White space is ignored (outside of string and character constants), and is therefore optional, except when it is used to separate tokens. This means that

are functionally the same program.

Although you must use white space to separate many tokens, no white space is required between operators and operands, nor is it required between other separators and that which they separate.

Furthermore, wherever one space is allowed, any amount of white space is allowed.

In string constants, spaces and tabs are not ignored; rather, they are part of the string. Therefore,

is not the same as

Next: Expressions and Operators , Previous: Lexical Elements , Up: Top   [ Contents ][ Index ]

2 Data Types

Next: Enumerations , Up: Data Types   [ Contents ][ Index ]

2.1 Primitive Data Types

Next: Real Number Types , Up: Primitive Types   [ Contents ][ Index ]

The integer data types range in size from at least 8 bits to at least 32 bits. The C99 standard extends this range to include integer sizes of at least 64 bits. You should use integer types for storing whole number values (and the char data type for storing characters). The sizes and ranges listed for these types are minimums; depending on your computer platform, these sizes and ranges may be larger.

While these ranges provide a natural ordering, the standard does not require that any two types have a different range. For example, it is common for int and long to have the same range. The standard even allows signed char and long to have the same range, though such platforms are very unusual.

  • signed char The 8-bit signed char data type can hold integer values in the range of -128 to 127.
  • unsigned char The 8-bit unsigned char data type can hold integer values in the range of 0 to 255.
  • char Depending on your system, the char data type is defined as having the same range as either the signed char or the unsigned char data type (they are three distinct types, however). By convention, you should use the char data type specifically for storing ASCII characters (such as `m' ), including escape sequences (such as `\n' ).
  • short int The 16-bit short int data type can hold integer values in the range of -32,768 to 32,767. You may also refer to this data type as short , signed short int , or signed short .
  • unsigned short int The 16-bit unsigned short int data type can hold integer values in the range of 0 to 65,535. You may also refer to this data type as unsigned short .
  • int The 32-bit int data type can hold integer values in the range of -2,147,483,648 to 2,147,483,647. You may also refer to this data type as signed int or signed .
  • unsigned int The 32-bit unsigned int data type can hold integer values in the range of 0 to 4,294,967,295. You may also refer to this data type simply as unsigned .
  • long int The 32-bit long int data type can hold integer values in the range of at least -2,147,483,648 to 2,147,483,647. (Depending on your system, this data type might be 64-bit, in which case its range is identical to that of the long long int data type.) You may also refer to this data type as long , signed long int , or signed long .
  • unsigned long int The 32-bit unsigned long int data type can hold integer values in the range of at least 0 to 4,294,967,295. (Depending on your system, this data type might be 64-bit, in which case its range is identical to that of the unsigned long long int data type.) You may also refer to this data type as unsigned long .
  • long long int The 64-bit long long int data type can hold integer values in the range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 . You may also refer to this data type as long long , signed long long int or signed long long . This type is not part of C89, but is both part of C99 and a GNU C extension.
  • unsigned long long int The 64-bit unsigned long long int data type can hold integer values in the range of at least 0 to 18,446,744,073,709,551,615 . You may also refer to this data type as unsigned long long . This type is not part of C89, but is both part of C99 and a GNU C extension.

Here are some examples of declaring and defining integer variables:

The first line declares an integer named foo but does not define its value; it is left uninitialized, and its value should not be assumed to be anything in particular.

Next: Complex Number Types , Previous: Integer Types , Up: Primitive Types   [ Contents ][ Index ]

There are three data types that represent fractional numbers. While the sizes and ranges of these types are consistent across most computer systems in use today, historically the sizes of these types varied from system to system. As such, the minimum and maximum values are stored in macro definitions in the library header file float.h . In this section, we include the names of the macro definitions in place of their possible values; check your system’s float.h for specific numbers.

  • float The float data type is the smallest of the three floating point types, if they differ in size at all. Its minimum value is stored in the FLT_MIN , and should be no greater than 1e-37 . Its maximum value is stored in FLT_MAX , and should be no less than 1e37 .
  • double The double data type is at least as large as the float type, and it may be larger. Its minimum value is stored in DBL_MIN , and its maximum value is stored in DBL_MAX .
  • long double The long double data type is at least as large as the float type, and it may be larger. Its minimum value is stored in LDBL_MIN , and its maximum value is stored in LDBL_MAX .

All floating point data types are signed; trying to use unsigned float , for example, will cause a compile-time error.

Here are some examples of declaring and defining real number variables:

The first line declares a float named foo but does not define its value; it is left uninitialized, and its value should not be assumed to be anything in particular.

The real number types provided in C are of finite precision, and accordingly, not all real numbers can be represented exactly. Most computer systems that GCC compiles for use a binary representation for real numbers, which is unable to precisely represent numbers such as, for example, 4.2. For this reason, we recommend that you consider not comparing real numbers for exact equality with the == operator, but rather check that real numbers are within an acceptable tolerance.

There are other more subtle implications of these imprecise representations; for more details, see David Goldberg’s paper What Every Computer Scientist Should Know About Floating-Point Arithmetic and section 4.2.2 of Donald Knuth’s The Art of Computer Programming .

Previous: Real Number Types , Up: Primitive Types   [ Contents ][ Index ]

2.1.3 Complex Number Types

GCC introduced some complex number types as an extension to C89. Similar features were introduced in C99 1 , but there were a number of differences. We describe the standard complex number types first.

Next: GNU Extensions for Complex Number Types , Up: Complex Number Types   [ Contents ][ Index ]

Complex types were introduced in C99. There are three complex types:

  • float _Complex
  • double _Complex
  • long double _Complex

The names here begin with an underscore and an uppercase letter in order to avoid conflicts with existing programs’ identifiers. However, the C99 standard header file <complex.h> introduces some macros which make using complex types easier.

  • complex Expands to _Complex . This allows a variable to be declared as double complex which seems more natural.
  • I A constant of type const float _Complex having the value of the imaginary unit normally referred to as i .

The <complex.h> header file also declares a number of functions for performing computations on complex numbers, for example the creal and cimag functions which respectively return the real and imaginary parts of a double complex number. Other functions are also provided, as shown in this example:

Previous: Standard Complex Number Types , Up: Complex Number Types   [ Contents ][ Index ]

GCC also introduced complex types as a GNU extension to C89, but the spelling is different. The floating-point complex types in GCC’s C89 extension are:

  • __complex__ float
  • __complex__ double
  • __complex__ long double

GCC’s extension allow for complex types other than floating-point, so that you can declare complex character types and complex integer types; in fact __complex__ can be used with any of the primitive data types. We won’t give you a complete list of all possibilities, but here are some examples:

  • __complex__ float The __complex__ float data type has two components: a real part and an imaginary part, both of which are of the float data type.
  • __complex__ int The __complex__ int data type also has two components: a real part and an imaginary part, both of which are of the int data type.

To extract the real part of a complex-valued expression, use the keyword __real__ , followed by the expression. Likewise, use __imag__ to extract the imaginary part.

This example creates a complex floating point variable a , and defines its real part as 4 and its imaginary part as 3. Then, the real part is assigned to the floating point variable b , and the imaginary part is assigned to the floating point variable c .

Next: Unions , Previous: Primitive Types , Up: Data Types   [ Contents ][ Index ]

2.2 Enumerations

An enumeration is a custom data type used for storing constant integer values and referring to them by names. By default, these values are of type signed int ; however, you can use the -fshort-enums GCC compiler option to cause the smallest possible integer type to be used instead. Both of these behaviors conform to the C89 standard, but mixing the use of these options within the same program can produce incompatibilities.

Next: Declaring Enumerations , Up: Enumerations   [ Contents ][ Index ]

You define an enumeration using the enum keyword, followed by the name of the enumeration (this is optional), followed by a list of constant names (separated by commas and enclosed in braces), and ending with a semicolon.

That example defines an enumeration, fruit , which contains four constant integer values, grape , cherry , lemon , and kiwi , whose values are, by default, 0, 1, 2, and 3, respectively. You can also specify one or more of the values explicitly:

That example defines banana to be -17, and the remaining values are incremented by 1: apple is -16, blueberry is -15, and mango is -14. Unless specified otherwise, an enumeration value is equal to one more than the previous value (and the first value defaults to 0).

You can also refer to an enumeration value defined earlier in the same enumeration:

In that example, kumquat is 0, raspberry is 1, peach is 2, and plum is 4.

You can’t use the same name for an enum as a struct or union in the same scope.

Previous: Defining Enumerations , Up: Enumerations   [ Contents ][ Index ]

You can declare variables of an enumeration type both when the enumeration is defined and afterward. This example declares one variable, named my_fruit of type enum fruit , all in a single statement:

while this example declares the type and variable separately:

(Of course, you couldn’t declare it that way if you hadn’t named the enumeration.)

Although such variables are considered to be of an enumeration type, you can assign them any value that you could assign to an int variable, including values from other enumerations. Furthermore, any variable that can be assigned an int value can be assigned a value from an enumeration.

However, you cannot change the values in an enumeration once it has been defined; they are constant values. For example, this won’t work:

Enumerations are useful in conjunction with the switch statement, because the compiler can warn you if you have failed to handle one of the enumeration values. Using the example above, if your code handles banana , apple and mango only but not blueberry , GCC can generate a warning.

Next: Structures , Previous: Enumerations , Up: Data Types   [ Contents ][ Index ]

A union is a custom data type used for storing several variables in the same memory space. Although you can access any of those variables at any time, you should only read from one of them at a time—assigning a value to one of them overwrites the values in the others.

Next: Declaring Union Variables , Up: Unions   [ Contents ][ Index ]

You define a union using the union keyword followed by the declarations of the union’s members, enclosed in braces. You declare each member of a union just as you would normally declare a variable—using the data type followed by one or more variable names separated by commas, and ending with a semicolon. Then end the union definition with a semicolon after the closing brace.

You should also include a name for the union between the union keyword and the opening brace. This is syntactically optional, but if you leave it out, you can’t refer to that union data type later on (without a typedef , see The typedef Statement ).

Here is an example of defining a simple union for holding an integer value and a floating point value:

That defines a union named numbers , which contains two members, i and f , which are of type int and float , respectively.

Next: Accessing Union Members , Previous: Defining Unions , Up: Unions   [ Contents ][ Index ]

2.3.2 Declaring Union Variables

You can declare variables of a union type when both you initially define the union and after the definition, provided you gave the union type a name.

Next: Declaring Union Variables After Definition , Up: Declaring Union Variables   [ Contents ][ Index ]

You can declare variables of a union type when you define the union type by putting the variable names after the closing brace of the union definition, but before the final semicolon. You can declare more than one such variable by separating the names with commas.

That example declares two variables of type union numbers , first_number and second_number .

Next: Initializing Union Members , Previous: Declaring Union Variables at Definition , Up: Declaring Union Variables   [ Contents ][ Index ]

You can declare variables of a union type after you define the union by using the union keyword and the name you gave the union type, followed by one or more variable names separated by commas.

Previous: Declaring Union Variables After Definition , Up: Declaring Union Variables   [ Contents ][ Index ]

You can initialize the first member of a union variable when you declare it:

In that example, the i member of first_number gets the value 5. The f member is left alone.

Another way to initialize a union member is to specify the name of the member to initialize. This way, you can initialize whichever member you want to, not just the first one. There are two methods that you can use—either follow the member name with a colon, and then its value, like this:

or precede the member name with a period and assign a value with the assignment operator, like this:

You can also initialize a union member when you declare the union variable during the definition:

Next: Size of Unions , Previous: Declaring Union Variables , Up: Unions   [ Contents ][ Index ]

You can access the members of a union variable using the member access operator. You put the name of the union variable on the left side of the operator, and the name of the member on the right side.

Notice in that example that giving a value to the f member overrides the value stored in the i member.

Previous: Accessing Union Members , Up: Unions   [ Contents ][ Index ]

This size of a union is equal to the size of its largest member. Consider the first union example from this section:

The size of the union data type is the same as sizeof (float) , because the float type is larger than the int type. Since all of the members of a union occupy the same memory space, the union data type size doesn’t need to be large enough to hold the sum of all their sizes; it just needs to be large enough to hold the largest member.

Next: Arrays , Previous: Unions , Up: Data Types   [ Contents ][ Index ]

2.4 Structures

A structure is a programmer-defined data type made up of variables of other data types (possibly including other structure types).

Next: Declaring Structure Variables , Up: Structures   [ Contents ][ Index ]

You define a structure using the struct keyword followed by the declarations of the structure’s members, enclosed in braces. You declare each member of a structure just as you would normally declare a variable—using the data type followed by one or more variable names separated by commas, and ending with a semicolon. Then end the structure definition with a semicolon after the closing brace.

You should also include a name for the structure in between the struct keyword and the opening brace. This is optional, but if you leave it out, you can’t refer to that structure data type later on (without a typedef , see The typedef Statement ).

Here is an example of defining a simple structure for holding the X and Y coordinates of a point:

That defines a structure type named struct point , which contains two members, x and y , both of which are of type int .

Structures (and unions) may contain instances of other structures and unions, but of course not themselves. It is possible for a structure or union type to contain a field which is a pointer to the same type (see Incomplete Types ).

Next: Accessing Structure Members , Previous: Defining Structures , Up: Structures   [ Contents ][ Index ]

2.4.2 Declaring Structure Variables

You can declare variables of a structure type when both you initially define the structure and after the definition, provided you gave the structure type a name.

Next: Declaring Structure Variables After Definition , Up: Declaring Structure Variables   [ Contents ][ Index ]

You can declare variables of a structure type when you define the structure type by putting the variable names after the closing brace of the structure definition, but before the final semicolon. You can declare more than one such variable by separating the names with commas.

That example declares two variables of type struct point , first_point and second_point .

Next: Initializing Structure Members , Previous: Declaring Structure Variables at Definition , Up: Declaring Structure Variables   [ Contents ][ Index ]

You can declare variables of a structure type after defining the structure by using the struct keyword and the name you gave the structure type, followed by one or more variable names separated by commas.

Previous: Declaring Structure Variables After Definition , Up: Declaring Structure Variables   [ Contents ][ Index ]

You can initialize the members of a structure type to have certain values when you declare structure variables.

If you do not initialize a structure variable, the effect depends on whether it has static storage (see Storage Class Specifiers ) or not. If it is, members with integral types are initialized with 0 and pointer members are initialized to NULL; otherwise, the value of the structure’s members is indeterminate.

One way to initialize a structure is to specify the values in a set of braces and separated by commas. Those values are assigned to the structure members in the same order that the members are declared in the structure in definition.

In that example, the x member of first_point gets the value 5, and the y member gets the value 10.

Another way to initialize the members is to specify the name of the member to initialize. This way, you can initialize the members in any order you like, and even leave some of them uninitialized. There are two methods that you can use. The first method is available in C99 and as a C89 extension in GCC:

You can also omit the period and use a colon instead of ‘ = ’, though this is a GNU C extension:

You can also initialize the structure variable’s members when you declare the variable during the structure definition:

You can also initialize fewer than all of a structure variable’s members:

Here, x is initialized with 5, y is initialized with 0, and p is initialized with NULL. The rule here is that y and p are initialized just as they would be if they were static variables.

Here is another example that initializes a structure’s members which are structure variables themselves:

That example defines the rectangle structure to consist of two point structure variables. Then it declares one variable of type struct rectangle and initializes its members. Since its members are structure variables, we used an extra set of braces surrounding the members that belong to the point structure variables. However, those extra braces are not necessary; they just make the code easier to read.

Next: Bit Fields , Previous: Declaring Structure Variables , Up: Structures   [ Contents ][ Index ]

You can access the members of a structure variable using the member access operator. You put the name of the structure variable on the left side of the operator, and the name of the member on the right side.

You can also access the members of a structure variable which is itself a member of a structure variable.

Next: Size of Structures , Previous: Accessing Structure Members , Up: Structures   [ Contents ][ Index ]

You can create structures with integer members of nonstandard sizes, called bit fields . You do this by specifying an integer ( int , char , long int , etc.) member as usual, and inserting a colon and the number of bits that the member should occupy in between the member’s name and the semicolon.

That example defines a structure type with two bit fields, suit and face_value , which take up 2 bits and 4 bits, respectively. suit can hold values from 0 to 3, and face_value can hold values from 0 to 15. Notice that these bit fields were declared as unsigned int ; had they been signed integers, then their ranges would have been from -2 to 1, and from -8 to 7, respectively.

More generally, the range of an unsigned bit field of N bits is from 0 to 2^N - 1 , and the range of a signed bit field of N bits is from -(2^N) / 2 to ((2^N) / 2) - 1 .

Bit fields can be specified without a name in order to control which actual bits within the containing unit are used. However, the effect of this is not very portable and it is rarely useful. You can also specify a bit field of size 0, which indicates that subsequent bit fields not further bit fields should be packed into the unit containing the previous bit field. This is likewise not generally useful.

You may not take the address of a bit field with the address operator & (see Pointer Operators ).

Previous: Bit Fields , Up: Structures   [ Contents ][ Index ]

The size of a structure type is equal to the sum of the size of all of its members, possibly including padding to cause the structure type to align to a particular byte boundary. The details vary depending on your computer platform, but it would not be atypical to see structures padded to align on four- or eight-byte boundaries. This is done in order to speed up memory accesses of instances of the structure type.

As a GNU extension, GCC allows structures with no members. Such structures have zero size.

If you wish to explicitly omit padding from your structure types (which may, in turn, decrease the speed of structure memory accesses), then GCC provides multiple methods of turning packing off. The quick and easy method is to use the -fpack-struct compiler option. For more details on omitting packing, please see the GCC manual which corresponds to your version of the compiler.

Next: Pointers , Previous: Structures , Up: Data Types   [ Contents ][ Index ]

An array is a data structure that lets you store one or more elements consecutively in memory. In C, array elements are indexed beginning at position zero, not one.

Next: Initializing Arrays , Up: Arrays   [ Contents ][ Index ]

You declare an array by specifying the data type for its elements, its name, and the number of elements it can store. Here is an example that declares an array that can store ten integers:

For standard C code, the number of elements in an array must be positive.

As a GNU extension, the number of elements can be as small as zero. Zero-length arrays are useful as the last element of a structure which is really a header for a variable-length object:

Another GNU extension allows you to declare an array size using variables, rather than only constants. For example, here is a function definition that declares an array using its parameter as the number of elements:

Next: Accessing Array Elements , Previous: Declaring Arrays , Up: Arrays   [ Contents ][ Index ]

You can initialize the elements in an array when you declare it by listing the initializing values, separated by commas, in a set of braces. Here is an example:

You don’t have to explicitly initialize all of the array elements. For example, this code initializes the first three elements as specified, and then initializes the last two elements to a default value of zero:

When using either ISO C99, or C89 with GNU extensions, you can initialize array elements out of order, by specifying which array indices to initialize. To do this, include the array index in brackets, and optionally the assignment operator, before the value. Here is an example:

Or, using the assignment operator:

Both of those examples are equivalent to:

When using GNU extensions, you can initialize a range of elements to the same value, by specifying the first and last indices, in the form [ first ] ... [ last ] . Here is an example:

That initializes elements 0 through 9 to 1, elements 10 through 98 to 2, and element 99 to 3. (You also could explicitly write [99] = 3 .) Also, notice that you must have spaces on both sides of the ‘ ... ’.

If you initialize every element of an array, then you do not have to specify its size; its size is determined by the number of elements you initialize. Here is an example:

Although this does not explicitly state that the array has five elements using my_array[5] , it initializes five elements, so that is how many it has.

Alternately, if you specify which elements to initialize, then the size of the array is equal to the highest element number initialized, plus one. For example:

In that example, only four elements are initialized, but the last one initialized is element number 99, so there are 100 elements.

Next: Multidimensional Arrays , Previous: Initializing Arrays , Up: Arrays   [ Contents ][ Index ]

You can access the elements of an array by specifying the array name, followed by the element index, enclosed in brackets. Remember that the array elements are numbered starting with zero. Here is an example:

That assigns the value 5 to the first element in the array, at position zero. You can treat individual array elements like variables of whatever data type the array is made up of. For example, if you have an array made of a structure data type, you can access the structure elements like this:

Next: Arrays as Strings , Previous: Accessing Array Elements , Up: Arrays   [ Contents ][ Index ]

You can make multidimensional arrays, or “arrays of arrays”. You do this by adding an extra set of brackets and array lengths for every additional dimension you want your array to have. For example, here is a declaration for a two-dimensional array that holds five elements in each dimension (a two-element array consisting of five-element arrays):

Multidimensional array elements are accessed by specifying the desired index of both dimensions:

In our example, two_dimensions[0] is itself an array. The element two_dimensions[0][2] is followed by two_dimensions[0][3] , not by two_dimensions[1][2] .

Next: Arrays of Unions , Previous: Multidimensional Arrays , Up: Arrays   [ Contents ][ Index ]

You can use an array of characters to hold a string (see String Constants ). The array may be built of either signed or unsigned characters.

When you declare the array, you can specify the number of elements it will have. That number will be the maximum number of characters that should be in the string, including the null character used to end the string. If you choose this option, then you do not have to initialize the array when you declare it. Alternately, you can simply initialize the array to a value, and its size will then be exactly large enough to hold whatever string you used to initialize it.

There are two different ways to initialize the array. You can specify of comma-delimited list of characters enclosed in braces, or you can specify a string literal enclosed in double quotation marks.

Here are some examples:

In each of these cases, the null character \0 is included at the end of the string, even when not explicitly stated. (Note that if you initialize a string using an array of individual characters, then the null character is not guaranteed to be present. It might be, but such an occurrence would be one of chance, and should not be relied upon.)

After initialization, you cannot assign a new string literal to an array using the assignment operator. For example, this will not work :

However, there are functions in the GNU C library that perform operations (including copy) on string arrays. You can also change one character at a time, by accessing individual string elements as you would any other array:

It is possible for you to explicitly state the number of elements in the array, and then initialize it using a string that has more characters than there are elements in the array. This is not a good thing. The larger string will not override the previously specified size of the array, and you will get a compile-time warning. Since the original array size remains, any part of the string that exceeds that original size is being written to a memory location that was not allocated for it.

Next: Arrays of Structures , Previous: Arrays as Strings , Up: Arrays   [ Contents ][ Index ]

You can create an array of a union type just as you can an array of a primitive data type.

That example creates a 3-element array of union numbers variables called number_array . You can also initialize the first members of the elements of a number array:

The additional inner grouping braces are optional.

After initialization, you can still access the union members in the array using the member access operator. You put the array name and element number (enclosed in brackets) to the left of the operator, and the member name to the right.

Previous: Arrays of Unions , Up: Arrays   [ Contents ][ Index ]

You can create an array of a structure type just as you can an array of a primitive data type.

That example creates a 3-element array of struct point variables called point_array . You can also initialize the elements of a structure array:

As with initializing structures which contain structure members, the additional inner grouping braces are optional. But, if you use the additional braces, then you can partially initialize some of the structures in the array, and fully initialize others:

In that example, the first element of the array has only its x member initialized. Because of the grouping braces, the value 4 is assigned to the x member of the second array element, not to the y member of the first element, as would be the case without the grouping braces.

After initialization, you can still access the structure members in the array using the member access operator. You put the array name and element number (enclosed in brackets) to the left of the operator, and the member name to the right.

Next: Incomplete Types , Previous: Arrays , Up: Data Types   [ Contents ][ Index ]

2.6 Pointers

Pointers hold memory addresses of stored constants or variables. For any data type, including both primitive types and custom types, you can create a pointer that holds the memory address of an instance of that type.

Next: Initializing Pointers , Up: Pointers   [ Contents ][ Index ]

You declare a pointer by specifying a name for it and a data type. The data type indicates of what type of variable the pointer will hold memory addresses.

To declare a pointer, include the indirection operator (see Pointer Operators ) before the identifier. Here is the general form of a pointer declaration:

White space is not significant around the indirection operator:

Here is an example of declaring a pointer to hold the address of an int variable:

Be careful, though: when declaring multiple pointers in the same statement, you must explicitly declare each as a pointer, using the indirection operator:

Next: Pointers to Unions , Previous: Declaring Pointers , Up: Pointers   [ Contents ][ Index ]

You can initialize a pointer when you first declare it by specifying a variable address to store in it. For example, the following code declares an int variable ‘ i ’, and a pointer which is initialized with the address of ‘ i ’:

Note the use of the address operator (see Pointer Operators ), used to get the memory address of a variable. After you declare a pointer, you do not use the indirection operator with the pointer’s name when assigning it a new address to point to. On the contrary, that would change the value of the variable that the points to, not the value of the pointer itself. For example:

The value stored in a pointer is an integral number: a location within the computer’s memory space. If you are so inclined, you can assign pointer values explicitly using literal integers, casting them to the appropriate pointer type. However, we do not recommend this practice unless you need to have extremely fine-tuned control over what is stored in memory, and you know exactly what you are doing. It would be all too easy to accidentally overwrite something that you did not intend to. Most uses of this technique are also non-portable.

It is important to note that if you do not initialize a pointer with the address of some other existing object, it points nowhere in particular and will likely make your program crash if you use it (formally, this kind of thing is called undefined behavior ).

Next: Pointers to Structures , Previous: Initializing Pointers , Up: Pointers   [ Contents ][ Index ]

You can create a pointer to a union type just as you can a pointer to a primitive data type.

That example creates a new union type, union numbers , and declares (and initializes the first member of) a variable of that type named foo . Finally, it declares a pointer to the type union numbers , and gives it the address of foo .

You can access the members of a union variable through a pointer, but you can’t use the regular member access operator anymore. Instead, you have to use the indirect member access operator (see Member Access Expressions ). Continuing with the previous example, the following example will change the value of the first member of foo :

Now the i member in foo is 450.

Previous: Pointers to Unions , Up: Pointers   [ Contents ][ Index ]

You can create a pointer to a structure type just as you can a pointer to a primitive data type.

That example creates a new structure type, struct fish , and declares (and initializes) a variable of that type named salmon . Finally, it declares a pointer to the type struct fish , and gives it the address of salmon .

You can access the members of a structure variable through a pointer, but you can’t use the regular member access operator anymore. Instead, you have to use the indirect member access operator (see Member Access Expressions ). Continuing with the previous example, the following example will change the values of the members of salmon :

Now the length and width members in salmon are 5.1 and 6.2, respectively.

Next: Type Qualifiers , Previous: Pointers , Up: Data Types   [ Contents ][ Index ]

You can define structures, unions, and enumerations without listing their members (or values, in the case of enumerations). Doing so results in an incomplete type. You can’t declare variables of incomplete types, but you can work with pointers to those types.

At some time later in your program you will want to complete the type. You do this by defining it as you usually would:

This technique is commonly used to for linked lists:

Next: Storage Class Specifiers , Previous: Incomplete Types , Up: Data Types   [ Contents ][ Index ]

There are two type qualifiers that you can prepend to your variable declarations which change how the variables may be accessed: const and volatile .

const causes the variable to be read-only; after initialization, its value may not be changed.

In addition to helping to prevent accidental value changes, declaring variables with const can aid the compiler in code optimization.

volatile tells the compiler that the variable is explicitly changeable, and seemingly useless accesses of the variable (for instance, via pointers) should not be optimized away. You might use volatile variables to store data that is updated via callback functions or signal handlers. Sequence Points and Signal Delivery .

Next: Renaming Types , Previous: Type Qualifiers , Up: Data Types   [ Contents ][ Index ]

There are four storage class specifiers that you can prepend to your variable declarations which change how the variables are stored in memory: auto , extern , register , and static .

You use auto for variables which are local to a function, and whose values should be discarded upon return from the function in which they are declared. This is the default behavior for variables declared within functions.

register is nearly identical in purpose to auto , except that it also suggests to the compiler that the variable will be heavily used, and, if possible, should be stored in a register. You cannot use the address-of operator to obtain the address of a variable declared with register . This means that you cannot refer to the elements of an array declared with storage class register . In fact the only thing you can do with such an array is measure its size with sizeof . GCC normally makes good choices about which values to hold in registers, and so register is not often used.

static is essentially the opposite of auto : when applied to variables within a function or block, these variables will retain their value even when the function or block is finished. This is known as static storage duration .

You can also declare variables (or functions) at the top level (that is, not inside a function) to be static ; such variables are visible (global) to the current source file (but not other source files). This gives an unfortunate double meaning to static ; this second meaning is known as static linkage . Two functions or variables having static linkage in separate files are entirely separate; neither is visible outside the file in which it is declared.

Uninitialized variables that are declared as extern are given default values of 0 , 0.0 , or NULL , depending on the type. Uninitialized variables that are declared as auto or register (including the default usage of auto ) are left uninitialized, and hence should not be assumed to hold any particular value.

extern is useful for declaring variables that you want to be visible to all source files that are linked into your project. You cannot initialize a variable in an extern declaration, as no space is actually allocated during the declaration. You must make both an extern declaration (typically in a header file that is included by the other source files which need to access the variable) and a non- extern declaration which is where space is actually allocated to store the variable. The extern declaration may be repeated multiple times.

See Program Structure and Scope , for related information.

Previous: Storage Class Specifiers , Up: Data Types   [ Contents ][ Index ]

Sometimes it is convenient to give a new name to a type. You can do this using the typedef statement. See The typedef Statement , for more information.

Next: Statements , Previous: Data Types , Up: Top   [ Contents ][ Index ]

3 Expressions and Operators

Next: Assignment Operators , Up: Expressions and Operators   [ Contents ][ Index ]

An expression consists of at least one operand and zero or more operators. Operands are typed objects such as constants, variables, and function calls that return values. Here are some examples:

Parentheses group subexpressions:

Innermost expressions are evaluated first. In the above example, 3 + 10 and 2 * 6 evaluate to 13 and 12 , respectively. Then 12 is subtracted from 13 , resulting in 1 . Finally, 1 is multiplied by 2 , resulting in 2 . The outermost parentheses are completely optional.

An operator specifies an operation to be performed on its operand(s). Operators may have one, two, or three operands, depending on the operator.

Next: Incrementing and Decrementing , Previous: Expressions , Up: Expressions and Operators   [ Contents ][ Index ]

Assignment operators store values in variables. C provides several variations of assignment operators.

The standard assignment operator = simply stores the value of its right operand in the variable specified by its left operand. As with all assignment operators, the left operand (commonly referred to as the “lvalue”) cannot be a literal or constant value.

Note that, unlike the other assignment operators described below, you can use the plain assignment operator to store values of a structure type.

Compound assignment operators perform an operation involving both the left and right operands, and then assign the resulting expression to the left operand. Here is a list of the compound assignment operators, and a brief description of what they do:

Adds the two operands together, and then assign the result of the addition to the left operand.

Subtract the right operand from the left operand, and then assign the result of the subtraction to the left operand.

Multiply the two operands together, and then assign the result of the multiplication to the left operand.

Divide the left operand by the right operand, and assign the result of the division to the left operand.

Perform modular division on the two operands, and assign the result of the division to the left operand.

Perform a left shift operation on the left operand, shifting by the number of bits specified by the right operand, and assign the result of the shift to the left operand.

Perform a right shift operation on the left operand, shifting by the number of bits specified by the right operand, and assign the result of the shift to the left operand.

Perform a bitwise conjunction operation on the two operands, and assign the result of the operation to the left operand.

Performs a bitwise exclusive disjunction operation on the two operands, and assign the result of the operation to the left operand.

Performs a bitwise inclusive disjunction operation on the two operands, and assign the result of the operation to the left operand.

Here is an example of using one of the compound assignment operators:

Since there are no side effects wrought by evaluating the variable x as an lvalue, the above code produces the same result as:

Next: Arithmetic Operators , Previous: Assignment Operators , Up: Expressions and Operators   [ Contents ][ Index ]

The increment operator ++ adds 1 to its operand. The operand must be a either a variable of one of the primitive data types, a pointer, or an enumeration variable. You can apply the increment operator either before or after the operand. Here are some examples:

(Note that incrementing a pointer only makes sense if you have reason to believe that the new pointer value will be a valid memory address.)

A prefix increment adds 1 before the operand is evaluated. A postfix increment adds 1 after the operand is evaluated. In the previous examples, changing the position of the operator would make no difference. However, there are cases where it does make a difference:

The output of the above example is:

Likewise, you can subtract 1 from an operand using the decrement operator:

The concepts of prefix and postfix application apply here as with the increment operator.

Next: Complex Conjugation , Previous: Incrementing and Decrementing , Up: Expressions and Operators   [ Contents ][ Index ]

C provides operators for standard arithmetic operations: addition, subtraction, multiplication, and division, along with modular division and negation. Usage of these operators is straightforward; here are some examples:

You can add and subtract memory pointers, but you cannot multiply or divide them.

Integer division of positive values truncates towards zero, so 5/3 is 1. However, if either operand is negative, the direction of rounding is implementation-defined. Signed Integer Division for information about overflow in signed integer division.

You use the modulus operator % to obtain the remainder produced by dividing its two operands. You put the operands on either side of the operator, and it does matter which operand goes on which side: 3 % 5 and 5 % 3 do not have the same result. The operands must be expressions of a primitive data type.

Modular division returns the remainder produced after performing integer division on the two operands. The operands must be of a primitive integer type.

If the operand you use with the negative operator is of an unsigned data type, then the result cannot negative, but rather is the maximum value of the unsigned data type, minus the value of the operand.

Many systems use twos-complement arithmetic, and on such systems the most negative value a signed type can hold is further away from zero than the most positive value. For example, on one platform, this program:

Produces this output:

Trivially, you can also apply a positive operator to a numeric expression:

Numeric values are assumed to be positive unless explicitly made negative, so this operator has no effect on program operation.

Next: Comparison Operators , Previous: Arithmetic Operators , Up: Expressions and Operators   [ Contents ][ Index ]

As a GNU extension, you can use the complex conjugation operator ~ to perform complex conjugation on its operand — that is, it reverses the sign of its imaginary component. The operand must be an expression of a complex number type. Here is an example:

Since an imaginary number (a + bi) multiplied by its conjugate is equal to a^2 + b^2 , the above printf statement will print 314, which is equal to 25 + 289 .

Next: Logical Operators , Previous: Complex Conjugation , Up: Expressions and Operators   [ Contents ][ Index ]

You use the comparison operators to determine how two operands relate to each other: are they equal to each other, is one larger than the other, is one smaller than the other, and so on. When you use any of the comparison operators, the result is either 1 or 0, meaning true or false, respectively.

(In the following code examples, the variables x and y stand for any two expressions of arithmetic types, or pointers.)

The equal-to operator == tests its two operands for equality. The result is 1 if the operands are equal, and 0 if the operands are not equal.

The not-equal-to operator != tests its two operands for inequality. The result is 1 if the operands are not equal, and 0 if the operands are equal.

Comparing floating-point values for exact equality or inequality can produce unexpected results. Real Number Types for more information.

You can compare function pointers for equality or inequality; the comparison tests if two function pointers point to the same function or not.

Beyond equality and inequality, there are operators you can use to test if one value is less than, greater than, less-than-or-equal-to, or greater-than-or-equal-to another value. Here are some code samples that exemplify usage of these operators:

Next: Bit Shifting , Previous: Comparison Operators , Up: Expressions and Operators   [ Contents ][ Index ]

Logical operators test the truth value of a pair of operands. Any nonzero expression is considered true in C, while an expression that evaluates to zero is considered false.

The logical conjunction operator && tests if two expressions are both true. If the first expression is false, then the second expression is not evaluated.

The logical disjunction operator || tests if at least one of two expressions it true. If the first expression is true, then the second expression is not evaluated.

You can prepend a logical expression with a negation operator ! to flip the truth value:

Since the second operand in a logical expression pair is not necessarily evaluated, you can write code with perhaps unintuitive results:

If foo is ever zero, then not only would bar not be called, but x would not be incremented. If you intend to increment x regardless of the value of foo , you should do so outside of the conjunction expression.

Next: Bitwise Logical Operators , Previous: Logical Operators , Up: Expressions and Operators   [ Contents ][ Index ]

You use the left-shift operator << to shift its first operand’s bits to the left. The second operand denotes the number of bit places to shift. Bits shifted off the left side of the value are discarded; new bits added on the right side will all be 0.

Similarly, you use the right-shift operator >> to shift its first operand’s bits to the right. Bits shifted off the right side are discarded; new bits added on the left side are usually 0, but if the first operand is a signed negative value, then the added bits will be either 0 or whatever value was previously in the leftmost bit position.

For both << and >> , if the second operand is greater than the bit-width of the first operand, or the second operand is negative, the behavior is undefined.

You can use the shift operators to perform a variety of interesting hacks. For example, given a date with the day of the month numbered as d , the month numbered as m , and the year y , you can store the entire date in a single number x :

You can then extract the original day, month, and year out of x using a combination of shift operators and modular division:

Next: Pointer Operators , Previous: Bit Shifting , Up: Expressions and Operators   [ Contents ][ Index ]

C provides operators for performing bitwise conjunction, inclusive disjunction, exclusive disjunction, and negation (complement).

Biwise conjunction examines each bit in its two operands, and when two corresponding bits are both 1, the resulting bit is 1. All other resulting bits are 0. Here is an example of how this works, using binary numbers:

Bitwise inclusive disjunction examines each bit in its two operands, and when two corresponding bits are both 0, the resulting bit is 0. All other resulting bits are 1.

Bitwise exclusive disjunction examines each bit in its two operands, and when two corresponding bits are different, the resulting bit is 1. All other resulting bits are 0.

Bitwise negation reverses each bit in its operand:

In C, you can only use these operators with operands of an integer (or character) type, and for maximum portability, you should only use the bitwise negation operator with unsigned integer types. Here are some examples of using these operators in C code:

Next: The sizeof Operator , Previous: Bitwise Logical Operators , Up: Expressions and Operators   [ Contents ][ Index ]

You can use the address operator & to obtain the memory address of an object.

It is not necessary to use this operator to obtain the address of a function, although you can:

Function pointers and data pointers are not compatible, in the sense that you cannot expect to store the address of a function into a data pointer, and then copy that into a function pointer and call it successfully. It might work on some systems, but it’s not a portable technique.

As a GNU extension to C89, you can also obtain the address of a label with the label address operator && . The result is a void* pointer which can be used with goto . See The goto Statement .

Given a memory address stored in a pointer, you can use the indirection operator * to obtain the value stored at the address. (This is called dereferencing the pointer.)

Avoid using dereferencing pointers that have not been initialized to a known memory location.

Next: Type Casts , Previous: Pointer Operators , Up: Expressions and Operators   [ Contents ][ Index ]

You can use the sizeof operator to obtain the size (in bytes) of the data type of its operand. The operand may be an actual type specifier (such as int or float ), as well as any valid expression. When the operand is a type name, it must be enclosed in parentheses. Here are some examples:

The result of the sizeof operator is of a type called size_t , which is defined in the header file <stddef.h> . size_t is an unsigned integer type, perhaps identical to unsigned int or unsigned long int ; it varies from system to system.

The size_t type is often a convenient type for a loop index, since it is guaranteed to be able to hold the number of elements in any array; this is not the case with int , for example.

The sizeof operator can be used to automatically compute the number of elements in an array:

There are two cases where this technique does not work. The first is where the array element has zero size (GCC supports zero-sized structures as a GNU extension). The second is where the array is in fact a function parameter (see Function Parameters ).

Next: Array Subscripts , Previous: The sizeof Operator , Up: Expressions and Operators   [ Contents ][ Index ]

You can use a type cast to explicitly cause an expression to be of a specified data type. A type cast consists of a type specifier enclosed in parentheses, followed by an expression. To ensure proper casting, you should also enclose the expression that follows the type specifier in parentheses. Here is an example:

In that example, since y and z are both integers, integer division is performed, and even though x is a floating-point variable, it receives the value 2. Explicitly casting the result of the division to float does no good, because the computed value of y/z is already 2.

To fix this problem, you need to convert one of the operands to a floating-point type before the division takes place:

Here, a floating-point value close to 2.333… is assigned to x .

Type casting only works with scalar types (that is, integer, floating-point or pointer types). Therefore, this is not allowed:

Next: Function Calls as Expressions , Previous: Type Casts , Up: Expressions and Operators   [ Contents ][ Index ]

You can access array elements by specifying the name of the array, and the array subscript (or index, or element number) enclosed in brackets. Here is an example, supposing an integer array called my_array :

The array subscript expression A[i] is defined as being identical to the expression (*((A)+(i))) . This means that many uses of an array name are equivalent to a pointer expression. It also means that you cannot subscript an array having the register storage class.

Next: The Comma Operator , Previous: Array Subscripts , Up: Expressions and Operators   [ Contents ][ Index ]

A call to any function which returns a value is an expression.

Next: Member Access Expressions , Previous: Function Calls as Expressions , Up: Expressions and Operators   [ Contents ][ Index ]

You use the comma operator , to separate two (ostensibly related) expressions. For instance, the first expression might produce a value that is used by the second expression:

More commonly, the comma operator is used in for statements, like this:

This lets you conveniently set, monitor, and modify multiple control expressions for the for statement.

A comma is also used to separate function parameters; however, this is not the comma operator in action. In fact, if the comma operator is used as we have discussed here in a function call, then the compiler will interpret that as calling the function with an extra parameter.

If you want to use the comma operator in a function argument, you need to put parentheses around it. That’s because commas in a function argument list have a different meaning: they separate arguments. Thus,

is interpreted as a function call with four arguments, but

is a function call with just three arguments. (The second argument is (y=47, x) .)

Next: Conditional Expressions , Previous: The Comma Operator , Up: Expressions and Operators   [ Contents ][ Index ]

You can use the member access operator . to access the members of a structure or union variable. You put the name of the structure variable on the left side of the operator, and the name of the member on the right side.

You can also access the members of a structure or union variable via a pointer by using the indirect member access operator -> . x->y is equivalent to (*x).y .

See Pointers .

Next: Statements and Declarations in Expressions , Previous: Member Access Expressions , Up: Expressions and Operators   [ Contents ][ Index ]

You use the conditional operator to cause the entire conditional expression to evaluate to either its second or its third operand, based on the truth value of its first operand. Here’s an example:

If expression a is true, then expression b is evaluated and the result is the value of b . Otherwise, expression c is evaluated and the result is c .

Expressions b and c must be compatible. That is, they must both be

  • arithmetic types
  • compatible struct or union types
  • pointers to compatible types (one of which might be the NULL pointer)

Alternatively, one operand is a pointer and the other is a void* pointer.

Here is an example

Here, if x equals 5, then a will receive the value of y . Otherwise, a will receive the value of z . This can be considered a shorthand method for writing a simple if … else statement. The following example will accomplish the same task as the previous one:

If the first operand of the conditional operator is true, then the third operand is never evaluated. Similarly, if the first operand is false, then the second operand is never evaluated. The first operand is always evaluated.

Next: Operator Precedence , Previous: Conditional Expressions , Up: Expressions and Operators   [ Contents ][ Index ]

As a GNU C extension, you can build an expression using compound statement enclosed in parentheses. This allows you to included loops, switches, and local variables within an expression.

Recall that a compound statement (also known as a block) is a sequence of statements surrounded by braces. In this construct, parentheses go around the braces. Here is an example:

That is a valid (though slightly more complex than necessary) expression for the absolute value of function () .

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void , and thus effectively no value.)

This feature is especially useful in making macro definitions “safe” (so that they evaluate each operand exactly once). For example, the “maximum” function is commonly defined as a macro in standard C as follows:

But this definition computes either a or b twice, with bad results if the operand has side effects. In GNU C, if you know the type of the operands (here let’s assume int ), you can define the macro safely as follows:

If you don’t know the type of the operand, you can still do this, but you must use typeof expressions or type naming.

Embedded statements are not allowed in constant expressions, such as the value of an enumeration constant, the width of a bit field, or the initial value of a static variable.

Next: Order of Evaluation , Previous: Statements and Declarations in Expressions , Up: Expressions and Operators   [ Contents ][ Index ]

When an expression contains multiple operators, such as a + b * f() , the operators are grouped based on rules of precedence . For instance, the meaning of that expression is to call the function f with no arguments, multiply the result by b , then add that result to a . That’s what the C rules of operator precedence determine for this expression.

The following is a list of types of expressions, presented in order of highest precedence first. Sometimes two or more operators have equal precedence; all those operators are applied from left to right unless stated otherwise.

  • Function calls, array subscripting, and membership access operator expressions.
  • Unary operators, including logical negation, bitwise complement, increment, decrement, unary positive, unary negative, indirection operator, address operator, type casting, and sizeof expressions. When several unary operators are consecutive, the later ones are nested within the earlier ones: !-x means !(-x) .
  • Multiplication, division, and modular division expressions.
  • Addition and subtraction expressions.
  • Bitwise shifting expressions.
  • Greater-than, less-than, greater-than-or-equal-to, and less-than-or-equal-to expressions.
  • Equal-to and not-equal-to expressions.
  • Bitwise AND expressions.
  • Bitwise exclusive OR expressions.
  • Bitwise inclusive OR expressions.
  • Logical AND expressions.
  • Logical OR expressions.
  • Conditional expressions (using ?: ). When used as subexpressions, these are evaluated right to left.
  • All assignment expressions, including compound assignment. When multiple assignment statements appear as subexpressions in a single larger expression, they are evaluated right to left.
  • Comma operator expressions.

The above list is somewhat dry and is apparently straightforward, but it does hide some pitfalls. Take this example:

Here p is incremented as a side effect of the expression, but foo takes the value of *(p++) rather than (*p)++ , since the unary operators bind right to left. There are other examples of potential surprises lurking behind the C precedence table. For this reason if there is the slightest risk of the reader misunderstanding the meaning of the program, you should use parentheses to make your meaning clear.

Previous: Operator Precedence , Up: Expressions and Operators   [ Contents ][ Index ]

3.20 Order of Evaluation

In C you cannot assume that multiple subexpressions are evaluated in the order that seems natural. For instance, consider the expression ++a * f() . Does this increment a before or after calling the function f ? The compiler could do it in either order, so you cannot make assumptions.

This manual explains the semantics of the C language in the abstract. However, an actual compiler translates source code into specific actions in an actual computer, and may re-order operations for the sake of efficiency. The correspondence between the program you write and the things the computer actually does are specified in terms of side effects and sequence points .

Next: Sequence Points , Up: Order of Evaluation   [ Contents ][ Index ]

A side effect is one of the following:

  • accessing a volatile object
  • modifying an object
  • modifying a file
  • a call to a function which performs any of the above side effects

These are essentially the externally-visible effects of running a program. They are called side effects because they are effects of expression evalation beyond the expression’s actual resulting value.

The compiler is allowed to perform the operations of your program in an order different to the order implied by the source of your program, provided that in the end all the necessary side effects actually take place. The compiler is also allowed to entirely omit some operations; for example it’s allowed to skip evaluating part of an expression if it can be certain that the value is not used and evaluating that part of the expression won’t produce any needed side effects.

Next: Sequence Points Constrain Expressions , Previous: Side Effects , Up: Order of Evaluation   [ Contents ][ Index ]

Another requirement on the compiler is that side effects should take place in the correct order. In order to provide this without over-constraining the compiler, the C89 and C90 standards specify a list of sequence points. A sequence point is one of the following:

  • a call to a function (after argument evaluation is complete)
  • the end of the left-hand operand of the and operator &&
  • the end of the left-hand operand of the or operator ||
  • the end of the left-hand operand of the comma operator ,
  • the end of the first operand of the ternary operator a ? b : c
  • the end of a full declarator 2
  • the end of an initialisation expression
  • the end of an expression statement (i.e. an expression followed by ; )
  • the end of the controlling expression of an if or switch statement
  • the end of the controlling expression of a while or do statement
  • the end of any of the three controlling expressions of a for statement
  • the end of the expression in a return statement
  • immediately before the return of a library function
  • after the actions associated with an item of formatted I/O (as used for example with the strftime or the printf and scanf famlies of functions).
  • immediately before and after a call to a comparison function (as called for example by qsort )

At a sequence point, all the side effects of previous expression evaluations must be complete, and no side effects of later evaluations may have taken place.

This may seem a little hard to grasp, but there is another way to consider this. Imagine you wrote a library (some of whose functions are external and perhaps others not) and compiled it, allowing someone else to call one of your functions from their code. The definitions above ensure that, at the time they call your function, the data they pass in has values which are consistent with the behaviour specified by the abstract machine, and any data returned by your function has a state which is also consistent with the abstract machine. This includes data accessible via pointers (i.e. not just function parameters and identifiers with external linkage).

The above is a slight simplification, since compilers exist that perform whole-program optimisation at link time. Importantly however, although they might perform optimisations, the visible side effects of the program must be the same as if they were produced by the abstract machine.

Next: Sequence Points and Signal Delivery , Previous: Sequence Points , Up: Order of Evaluation   [ Contents ][ Index ]

The code fragment

is quite normal and no doubt occurs in many programs. However, the quite similar code fragment

is a little harder to understand; what is the final value of i ? The C standards (both C89 and C99) both forbid this construct in conforming programs.

Between two sequence points,

  • an object may have its stored value modified at most once by the evaluation of an expression
  • the prior value of the object shall be read only to determine the value to be stored.

The first of these two conditions forbids expressions like foo(x=2, ++x) . The second condition forbids expressions like a[i++] = i .

Not allowed in a conforming program; modifies x twice before argument evaluation is complete.

Allowed; the function bar takes one argument (the value 2 is passed here), and there is a sequence point at the comma operator.

Allowed; there is a sequence point at || .

Allowed; there is a sequence point after the full declarator of x .

Allowed; there is a sequence point at the end of the first expression statement.

Allowed; there is a sequence point at the end of the controlling expression of the if 3 .

Allowed; there is a sequence point before the ? , and only one of the two following expressions is evaluated.

Not allowed; the object at p is being modified twice before the evaluation of the arguments to bar is complete. The fact that this is done once via p and once via q is irrelevant, since they both point to the same object.

Let’s go back to the example we used to introduce the problem of the order of evaluation, ++a * f() . Suppose the code actually looks like this:

Is this code allowed in a standard-conforming program? Although the expression in foo modifies a twice, this is not a problem. Let’s look at the two possible cases.

Since f returns a value other than void, it must contain a return statement. Therefore, there is a sequence point at the end of the return expression. That comes between the modification to a that f makes and the evaluation of the left operand.

First, a is incremented. Then the arguments to f are evaluated (there are zero of them). Then there is a sequence point before f is actually called.

So, we see that our program is standard-conforming. Notice that the above argument does not actually depend on the details of the body of the function f . It only depends on the function containing something ending in a sequence point – in our example this is a return statement, but an expression statement or a full declarator would do just as well.

However, the result of executing this code depends on the order of evaluation of the operands of * . If the left-hand operand is evaluated first, foo returns 6. Otherwise, it returns 303. The C standard does not specify in which order the operands should be evaluated, and also does not require an implementation either to document the order or even to stick to one order. The effect of this code is unspecified , meaning that one of several specific things will happen, but the C standards do not say which.

Previous: Sequence Points Constrain Expressions , Up: Order of Evaluation   [ Contents ][ Index ]

Signals are mainly documented in the GNU C Library manual rather than this document, even though the C standards consider the compiler and the C library together to be “the implementation”.

When a signal is received, this will happen between sequence points. Side effects on volatile objects prior to the previous sequence point will have occurred, but other updates may not have occurred yet. This even applies to straight assignments, such as x=0; , because the code generated for that statement may require more than one instruction, meaning that it can be interrupted part-way through by the delivery of a signal.

The C standard is quite restrictive about what data access can occur within a signal handler. They can of course use auto variables, but in terms of reading or writing other objects, they must be volatile sig_atomic_t . The volatile type qualifier ensures that access to the variable in the other parts of the program doesn’t span sequence points and the use of the sig_atomic_t type ensures that changes to the variable are atomic with respect to signal delivery.

The POSIX standard also allows a small number of library functions to be called from a signal handler. These functions are referred to as the set of async-signal-safe functions. If your program is intended to run on a POSIX system but not on other systems, you can safely call these from your signal handler too.

Next: Functions , Previous: Expressions and Operators , Up: Top   [ Contents ][ Index ]

4 Statements

You write statements to cause actions and to control flow within your programs. You can also write statements that do not do anything at all, or do things that are uselessly trivial.

Next: Expression Statements , Up: Statements   [ Contents ][ Index ]

You can use labels to identify a section of source code for use with a later goto (see The goto Statement ). A label consists of an identifier (such as those used for variable names) followed by a colon. Here is an example:

You should be aware that label names do not interfere with other identifier names:

The ISO C standard mandates that a label must be followed by at least one statement, possibly a null statement (see The Null Statement ). GCC will compile code that does not meet this requirement, but be aware that if you violate it, your code may have portability issues.

Next: The if Statement , Previous: Labels , Up: Statements   [ Contents ][ Index ]

You can turn any expression into a statement by adding a semicolon to the end of the expression. Here are some examples:

In each of those, all that happens is that each expression is evaluated. However, they are useless because they do not store a value anywhere, nor do they actually do anything, other than the evaluation itself. The compiler is free to ignore such statements.

Expression statements are only useful when they have some kind of side effect, such as storing a value, calling a function, or (this is esoteric) causing a fault in the program. Here are some more useful examples:

The last of those statements, *cucumber; , could potentially cause a fault in the program if the value of cucumber is both not a valid pointer and has been declared as volatile .

Next: The switch Statement , Previous: Expression Statements , Up: Statements   [ Contents ][ Index ]

You can use the if statement to conditionally execute part of your program, based on the truth value of a given expression. Here is the general form of an if statement:

If test evaluates to true, then then-statement is executed and else-statement is not. If test evaluates to false, then else-statement is executed and then-statement is not. The else clause is optional.

Here is an actual example:

If x == 10 evaluates to true, then the statement puts ("x is 10"); is executed. If x == 10 evaluates to false, then the statement puts ("x is 10"); is not executed.

Here is an example using else :

You can use a series of if statements to test for multiple conditions:

This function calculates and displays the date of Easter for the given year y :

Next: The while Statement , Previous: The if Statement , Up: Statements   [ Contents ][ Index ]

You can use the switch statement to compare one expression with others, and then execute a series of sub-statements based on the result of the comparisons. Here is the general form of a switch statement:

The switch statement compares test to each of the compare expressions, until it finds one that is equal to test . Then, the statements following the successful case are executed. All of the expressions compared must be of an integer type, and the compare-N expressions must be of a constant integer type (e.g., a literal integer or an expression built of literal integers).

Optionally, you can specify a default case. If test doesn’t match any of the specific cases listed prior to the default case, then the statements for the default case are executed. Traditionally, the default case is put after the specific cases, but that isn’t required.

Notice the usage of the break statement in each of the cases. This is because, once a matching case is found, not only are its statements executed, but so are the statements for all following cases:

The output of that example is:

This is often not desired. Including a break statement at the end of each case redirects program flow to after the switch statement.

As a GNU C extension, you can also specify a range of consecutive integer values in a single case label, like this:

This has the same effect as the corresponding number of individual case labels, one for each integer value from low to high , inclusive.

This feature is especially useful for ranges of ASCII character codes:

Be careful to include spaces around the ... ; otherwise it may be parsed incorrectly when you use it with integer values. For example, write this:

instead of this:

It is common to use a switch statement to handle various possible values of errno . In this case a portable program should watch out for the possibility that two macros for errno values in fact have the same value, for example EWOULDBLOCK and EAGAIN .

Next: The do Statement , Previous: The switch Statement , Up: Statements   [ Contents ][ Index ]

The while statement is a loop statement with an exit test at the beginning of the loop. Here is the general form of the while statement:

The while statement first evaluates test . If test evaluates to true, statement is executed, and then test is evaluated again. statement continues to execute repeatedly as long as test is true after each execution of statement .

This example prints the integers from zero through nine:

A break statement can also cause a while loop to exit.

Next: The for Statement , Previous: The while Statement , Up: Statements   [ Contents ][ Index ]

The do statement is a loop statement with an exit test at the end of the loop. Here is the general form of the do statement:

The do statement first executes statement . After that, it evaluates test . If test is true, then statement is executed again. statement continues to execute repeatedly as long as test is true after each execution of statement .

This example also prints the integers from zero through nine:

A break statement can also cause a do loop to exit.

Next: Blocks , Previous: The do Statement , Up: Statements   [ Contents ][ Index ]

The for statement is a loop statement whose structure allows easy variable initialization, expression testing, and variable modification. It is very convenient for making counter-controlled loops. Here is the general form of the for statement:

The for statement first evaluates the expression initialize . Then it evaluates the expression test . If test is false, then the loop ends and program control resumes after statement . Otherwise, if test is true, then statement is executed. Finally, step is evaluated, and the next iteration of the loop begins with evaluating test again.

Most often, initialize assigns values to one or more variables, which are generally used as counters, test compares those variables to a predefined expression, and step modifies those variables’ values. Here is another example that prints the integers from zero through nine:

First, it evaluates initialize , which assigns x the value 0. Then, as long as x is less than 10, the value of x is printed (in the body of the loop). Then x is incremented in the step clause and the test re-evaluated.

All three of the expressions in a for statement are optional, and any combination of the three is valid. Since the first expression is evaluated only once, it is perhaps the most commonly omitted expression. You could also write the above example as:

In this example, x receives its value prior to the beginning of the for statement.

If you leave out the test expression, then the for statement is an infinite loop (unless you put a break or goto statement somewhere in statement ). This is like using 1 as test ; it is never false.

This for statement starts printing numbers at 1 and then continues indefinitely, always printing x incremented by 1:

If you leave out the step expression, then no progress is made toward completing the loop—at least not as is normally expected with a for statement.

This example prints the number 1 over and over, indefinitely:

Perhaps confusingly, you cannot use the comma operator (see The Comma Operator ) for monitoring multiple variables in a for statement, because as usual the comma operator discards the result of its left operand. This loop:

If you need to test two conditions, you will need to use the && operator:

A break statement can also cause a for loop to exit.

Here is an example of a function that computes the summation of squares, given a starting integer to square and an ending integer to square:

Next: The Null Statement , Previous: The for Statement , Up: Statements   [ Contents ][ Index ]

A block is a set of zero or more statements enclosed in braces. Blocks are also known as compound statements . Often, a block is used as the body of an if statement or a loop statement, to group statements together.

You can also put blocks inside other blocks:

You can declare variables inside a block; such variables are local to that block. In C89, declarations must occur before other statements, and so sometimes it is useful to introduce a block simply for this purpose:

Next: The goto Statement , Previous: Blocks , Up: Statements   [ Contents ][ Index ]

The null statement is merely a semicolon alone.

A null statement does not do anything. It does not store a value anywhere. It does not cause time to pass during the execution of your program.

Most often, a null statement is used as the body of a loop statement, or as one or more of the expressions in a for statement. Here is an example of a for statement that uses the null statement as the body of the loop (and also calculates the integer square root of n , just for fun):

Here is another example that uses the null statement as the body of a for loop and also produces output:

A null statement is also sometimes used to follow a label that would otherwise be the last thing in a block.

Next: The break Statement , Previous: The Null Statement , Up: Statements   [ Contents ][ Index ]

You can use the goto statement to unconditionally jump to a different place in the program. Here is the general form of a goto statement:

You have to specify a label to jump to; when the goto statement is executed, program control jumps to that label. See Labels . Here is an example:

The label can be anywhere in the same function as the goto statement that jumps to it, but a goto statement cannot jump to a label in a different function.

You can use goto statements to simulate loop statements, but we do not recommend it—it makes the program harder to read, and GCC cannot optimize it as well. You should use for , while , and do statements instead of goto statements, when possible.

As an extension, GCC allows a goto statement to jump to an address specified by a void* variable. To make this work, you also need to take the address of a label by using the unary operator && (not & ). Here is a contrived example:

Next: The continue Statement , Previous: The goto Statement , Up: Statements   [ Contents ][ Index ]

You can use the break statement to terminate a while , do , for , or switch statement. Here is an example:

That example prints numbers from 1 to 7. When x is incremented to 8, x == 8 is true, so the break statement is executed, terminating the for loop prematurely.

If you put a break statement inside of a loop or switch statement which itself is inside of a loop or switch statement, the break only terminates the innermost loop or switch statement.

Next: The return Statement , Previous: The break Statement , Up: Statements   [ Contents ][ Index ]

You can use the continue statement in loops to terminate an iteration of the loop and begin the next iteration. Here is an example:

If you put a continue statement inside a loop which itself is inside a loop, then it affects only the innermost loop.

Next: The typedef Statement , Previous: The continue Statement , Up: Statements   [ Contents ][ Index ]

You can use the return statement to end the execution of a function and return program control to the function that called it. Here is the general form of the return statement:

return-value is an optional expression to return. If the function’s return type is void , then it is invalid to return an expression. You can, however, use the return statement without a return value.

If the function’s return type is not the same as the type of return-value , and automatic type conversion cannot be performed, then returning return-value is invalid.

If the function’s return type is not void and no return value is specified, then the return statement is valid unless the function is called in a context that requires a return value. For example:

In that case, the function cosine was called in a context that required a return value, so the value could be assigned to x .

Even in contexts where a return value is not required, it is a bad idea for a non- void function to omit the return value. With GCC, you can use the command line option -Wreturn -type to issue a warning if you omit the return value in such functions.

Here are some examples of using the return statement, in both a void and non- void function:

Previous: The return Statement , Up: Statements   [ Contents ][ Index ]

You can use the typedef statement to create new names for data types. Here is the general form of the typedef statement:

old-type-name is the existing name for the type, and may consist of more than one token (e.g., unsigned long int ). new-type-name is the resulting new name for the type, and must be a single identifier. Creating this new name for the type does not cause the old name to cease to exist. Here are some examples:

In the case of custom data types, you can use typedef to make a new name for the type while defining the type:

To make a type definition of an array, you first provide the type of the element, and then establish the number of elements at the end of the type definition:

When selecting names for types, you should avoid ending your type names with a _t suffix. The compiler will allow you to do this, but the POSIX standard reserves use of the _t suffix for standard library type names.

Next: Program Structure and Scope , Previous: Statements , Up: Top   [ Contents ][ Index ]

5 Functions

You can write functions to separate parts of your program into distinct subprocedures. To write a function, you must at least create a function definition. It is a good idea also to have an explicit function declaration; you don’t have to, but if you leave it out, then the default implicit declaration might not match the function itself, and you will get some compile-time warnings.

Every program requires at least one function, called main . That is where the program’s execution begins.

Next: Function Definitions , Up: Functions   [ Contents ][ Index ]

You write a function declaration to specify the name of a function, a list of parameters, and the function’s return type. A function declaration ends with a semicolon. Here is the general form:

return-type indicates the data type of the value returned by the function. You can declare a function that doesn’t return anything by using the return type void .

function-name can be any valid identifier (see Identifiers ).

parameter-list consists of zero or more parameters, separated by commas. A typical parameter consists of a data type and an optional name for the parameter. You can also declare a function that has a variable number of parameters (see Variable Length Parameter Lists ), or no parameters using void . Leaving out parameter-list entirely also indicates no parameters, but it is better to specify it explicitly with void .

Here is an example of a function declaration with two parameters:

If you include a name for a parameter, the name immediately follows the data type, like this:

The parameter names can be any identifier (see Identifiers ), and if you have more than one parameter, you can’t use the same name more than once within a single declaration. The parameter names in the declaration need not match the names in the definition.

You should write the function declaration above the first use of the function. You can put it in a header file and use the #include directive to include that function declaration in any source code files that use the function.

Next: Calling Functions , Previous: Function Declarations , Up: Functions   [ Contents ][ Index ]

You write a function definition to specify what a function actually does. A function definition consists of information regarding the function’s name, return type, and types and names of parameters, along with the body of the function. The function body is a series of statements enclosed in braces; in fact it is simply a block (see Blocks ).

Here is the general form of a function definition:

return-type and function-name are the same as what you use in the function declaration (see Function Declarations ).

parameter-list is the same as the parameter list used in the function declaration (see Function Declarations ), except you must include names for the parameters in a function definition.

Here is an simple example of a function definition—it takes two integers as its parameters and returns the sum of them as its return value:

For compatibility with the original design of C, you can also specify the type of the function parameters after the closing parenthesis of the parameter list, like this:

However, we strongly discourage this style of coding; it can cause subtle problems with type casting, among other problems.

Next: Function Parameters , Previous: Function Definitions , Up: Functions   [ Contents ][ Index ]

You can call a function by using its name and supplying any needed parameters. Here is the general form of a function call:

A function call can make up an entire statement, or it can be used as a subexpression. Here is an example of a standalone function call:

In that example, the function ‘ foo ’ is called with the parameter 5 .

Here is an example of a function call used as a subexpression:

Supposing that the function ‘ square ’ squares its parameter, the above example assigns the value 25 to a .

If a parameter takes more than one argument, you separate parameters with commas:

Next: Variable Length Parameter Lists , Previous: Calling Functions , Up: Functions   [ Contents ][ Index ]

Function parameters can be any expression—a literal value, a value stored in variable, an address in memory, or a more complex expression built by combining these.

Within the function body, the parameter is a local copy of the value passed into the function; you cannot change the value passed in by changing the local copy.

In that example, even though the parameter a is modified in the function ‘ foo ’, the variable x that is passed to the function does not change. If you wish to use the function to change the original value of x , then you would have to incorporate the function call into an assignment statement:

If the value that you pass to a function is a memory address (that is, a pointer), then you can access (and change) the data stored at the memory address. This achieves an effect similar to pass-by-reference in other languages, but is not the same: the memory address is simply a value, just like any other value, and cannot itself be changed. The difference between passing a pointer and passing an integer lies in what you can do using the value within the function.

Here is an example of calling a function with a pointer parameter:

The formal parameter for the function is of type pointer-to- int , and we call the function by passing it the address of a variable of type int . By dereferencing the pointer within the function body, we can both see and change the value stored in the address. The above changes the value of a to ‘ 57 ’.

Even if you don’t want to change the value stored in the address, passing the address of a variable rather than the variable itself can be useful if the variable type is large and you need to conserve memory space or limit the performance impact of parameter copying. For example:

In this case, unless you are working on a computer with very large memory addresses, it will take less memory to pass a pointer to the structure than to pass an instance of the structure.

One type of parameter that is always passed as a pointer is any sort of array:

In this example, calling the function foo with the parameter a does not copy the entire array into a new local parameter within foo ; rather, it passes x as a pointer to the first element in x . Be careful, though: within the function, you cannot use sizeof to determine the size of the array x — sizeof instead tells you the size of the pointer x . Indeed, the above code is equivalent to:

Explicitly specifying the length of the array in the parameter declaration will not help. If you really need to pass an array by value, you can wrap it in a struct , though doing this will rarely be useful (passing a const -qualified pointer is normally sufficient to indicate that the caller should not modify the array).

Next: Calling Functions Through Function Pointers , Previous: Function Parameters , Up: Functions   [ Contents ][ Index ]

You can write a function that takes a variable number of arguments; these are called variadic functions . To do this, the function needs to have at least one parameter of a known data type, but the remaining parameters are optional, and can vary in both quantity and data type.

You list the initial parameters as normal, but then after that, use an ellipsis: ‘ ... ’. Here is an example function prototype:

To work with the optional parameters in the function definition, you need to use macros that are defined in the library header file ‘ <stdarg.h> ’, so you must #include that file. For a detailed description of these macros, see The GNU C Library manual’s section on variadic functions.

Here is an example:

To use optional parameters, you need to have a way to know how many there are. This can vary, so it can’t be hard-coded, but if you don’t know how many optional parameters you have, then you could have difficulty knowing when to stop using the ‘ va_arg ’ function. In the above example, the first parameter to the ‘ add_multiple_values ’ function, ‘ number ’, is the number of optional parameters actually passed. So, we might call the function like this:

The first parameter indicates how many optional parameters follow it.

Also, note that you don’t actually need to use ‘ va_end ’ function. In fact, with GCC it doesn’t do anything at all. However, you might want to include it to maximize compatibility with other compilers.

See Variadic Functions in The GNU C Library Reference Manual .

Next: The main Function , Previous: Variable Length Parameter Lists , Up: Functions   [ Contents ][ Index ]

You can also call a function identified by a pointer. The indirection operator * is optional when doing this.

Next: Recursive Functions , Previous: Calling Functions Through Function Pointers , Up: Functions   [ Contents ][ Index ]

Every program requires at least one function, called ‘ main ’. This is where the program begins executing. You do not need to write a declaration or prototype for main , but you do need to define it.

The return type for main is always int . You do not have to specify the return type for main , but you can. However, you cannot specify that it has a return type other than int .

In general, the return value from main indicates the program’s exit status . A value of zero or EXIT_SUCCESS indicates success and EXIT_FAILURE indicates an error. Otherwise, the significance of the value returned is implementation-defined.

Reaching the } at the end of main without a return, or executing a return statement with no value (that is, return; ) are both equivalent. In C89, the effect of this is undefined, but in C99 the effect is equivalent to return 0; .

You can write your main function to have no parameters (that is, as int main (void) ), or to accept parameters from the command line. Here is a very simple main function with no parameters:

To accept command line parameters, you need to have two parameters in the main function, int argc followed by char *argv[] . You can change the names of those parameters, but they must have those data types— int and array of pointers to char . argc is the number of command line parameters, including the name of the program itself. argv is an array of the parameters, as character strings. argv[0] , the first element in the array, is the name of the program as typed at the command line 4 ; any following array elements are the parameters that followed the name of the program.

Here is an example main function that accepts command line parameters, and prints out what those parameters are:

Next: Static Functions , Previous: The main Function , Up: Functions   [ Contents ][ Index ]

You can write a function that is recursive—a function that calls itself. Here is an example that computes the factorial of an integer:

Be careful that you do not write a function that is infinitely recursive. In the above example, once x is 1, the recursion stops. However, in the following example, the recursion does not stop until the program is interrupted or runs out of memory:

Functions can also be indirectly recursive, of course.

Next: Nested Functions , Previous: Recursive Functions , Up: Functions   [ Contents ][ Index ]

You can define a function to be static if you want it to be callable only within the source file where it is defined:

This is useful if you are building a reusable library of functions and need to include some subroutines that should not be callable by the end user.

Functions which are defined in this way are said to have static linkage . Unfortunately the static keyword has multiple meanings; Storage Class Specifiers .

Previous: Static Functions , Up: Functions   [ Contents ][ Index ]

As a GNU C extension, you can define functions within other functions, a technique known as nesting functions.

Here is an example of a tail-recursive factorial function, defined using a nested function:

Note that nested functions must be defined along with variable declarations at the beginning of a function, and all other statements follow.

Next: A Sample Program , Previous: Functions , Up: Top   [ Contents ][ Index ]

6 Program Structure and Scope

Now that we have seen all of the fundamental elements of C programs, it’s time to look at the big picture.

Next: Scope , Up: Program Structure and Scope   [ Contents ][ Index ]

A C program may exist entirely within a single source file, but more commonly, any non-trivial program will consist of several custom header files and source files, and will also include and link with files from existing libraries.

By convention, header files (with a “.h” extension) contain variable and function declarations, and source files (with a “.c” extension) contain the corresponding definitions. Source files may also store declarations, if these declarations are not for objects which need to be seen by other files. However, header files almost certainly should not contain any definitions.

For example, if you write a function that computes square roots, and you wanted this function to be accessible to files other than where you define the function, then you would put the function declaration into a header file (with a “.h” file extension):

This header file could be included by other source files which need to use your function, but do not need to know how it was implemented.

The implementation of the function would then go into a corresponding source file (with a “.c” file extension):

Previous: Program Structure , Up: Program Structure and Scope   [ Contents ][ Index ]

Scope refers to what parts of the program can “see” a declared object. A declared object can be visible only within a particular function, or within a particular file, or may be visible to an entire set of files by way of including header files and using extern declarations.

Unless explicitly stated otherwise, declarations made at the top-level of a file (i.e., not within a function) are visible to the entire file, including from within functions, but are not visible outside of the file.

Declarations made within functions are visible only within those functions.

A declaration is not visible to declarations that came before it; for example:

will work, but:

See Storage Class Specifiers , for more information on changing the scope of declared objects. Also see Static Functions .

Next: Overflow , Previous: Program Structure and Scope , Up: Top   [ Contents ][ Index ]

7 A Sample Program

To conclude our description of C, here is a complete program written in C, consisting of both a C source file and a header file. This program is an expanded version of the quintessential “hello world” program, and serves as an example of how to format and structure C code for use in programs for FSF Project GNU. (You can always download the most recent version of this program, including sample makefiles and other examples of how to produce GNU software, from http://www.gnu.org/software/hello .)

This program uses features of the preprocessor; for a description of preprocessor macros, see The C Preprocessor , available as part of the GCC documentation.

Next: system.h , Up: A Sample Program   [ Contents ][ Index ]

Previous: hello.c , Up: A Sample Program   [ Contents ][ Index ]

Next: GNU Free Documentation License , Previous: A Sample Program , Up: Top   [ Contents ][ Index ]

Appendix A Overflow

[This appendix, written principally by Paul Eggert, is from the GNU Autoconf manual. We thought that it would be helpful to include here. –TJR]

In practice many portable C programs assume that signed integer overflow wraps around reliably using two’s complement arithmetic. Yet the C standard says that program behavior is undefined on overflow, and in a few cases C programs do not work on some modern implementations because their overflows do not wrap around as their authors expected. Conversely, in signed integer remainder, the C standard requires overflow behavior that is commonly not implemented.

Next: Signed Overflow Examples , Up: Overflow   [ Contents ][ Index ]

In languages like C, unsigned integer overflow reliably wraps around; e.g., UINT_MAX + 1 yields zero. This is guaranteed by the C standard and is portable in practice, unless you specify aggressive, nonstandard optimization options suitable only for special applications.

In contrast, the C standard says that signed integer overflow leads to undefined behavior where a program can do anything, including dumping core or overrunning a buffer. The misbehavior can even precede the overflow. Such an overflow can occur during addition, subtraction, multiplication, division, and left shift.

Despite this requirement of the standard, many C programs assume that signed integer overflow silently wraps around modulo a power of two, using two’s complement arithmetic, so long as you cast the resulting value to a signed integer type or store it into a signed integer variable. If you use conservative optimization flags, such programs are generally portable to the vast majority of modern platforms, with a few exceptions discussed later.

For historical reasons the C standard also allows implementations with ones’ complement or signed magnitude arithmetic, but it is safe to assume two’s complement nowadays.

Also, overflow can occur when converting an out-of-range value to a signed integer type. Here a standard implementation must define what happens, but this might include raising an exception. In practice all known implementations support silent wraparound in this case, so you need not worry about other possibilities.

Next: Optimization and Wraparound , Previous: Integer Overflow Basics , Up: Overflow   [ Contents ][ Index ]

There has long been a tension between what the C standard requires for signed integer overflow, and what C programs commonly assume. The standard allows aggressive optimizations based on assumptions that overflow never occurs, but many practical C programs rely on overflow wrapping around. These programs do not conform to the standard, but they commonly work in practice because compiler writers are understandably reluctant to implement optimizations that would break many programs, unless perhaps a user specifies aggressive optimization.

The C Standard says that if a program has signed integer overflow its behavior is undefined, and the undefined behavior can even precede the overflow. To take an extreme example:

If the int variable counter equals INT_MAX , counter++ must overflow and the behavior is undefined, so the C standard allows the compiler to optimize away the test against INT_MAX and the abort call. Worse, if an earlier bug in the program lets the compiler deduce that counter == INT_MAX or that counter previously overflowed, the C standard allows the compiler to optimize away the password test and generate code that allows superuser privileges unconditionally.

Despite this requirement by the standard, it has long been common for C code to assume wraparound arithmetic after signed overflow, and all known practical C implementations support some C idioms that assume wraparound signed arithmetic, even if the idioms do not conform strictly to the standard. If your code looks like the following examples it will almost surely work with real-world compilers.

Here is an example derived from the 7th Edition Unix implementation of atoi (1979-01-10):

Even if the input string is in range, on most modern machines this has signed overflow when computing the most negative integer (the -n overflows) or a value near an extreme integer (the first + overflows).

Here is another example, derived from the 7th Edition implementation of rand (1979-01-10). Here the programmer expects both multiplication and addition to wrap on overflow:

In the following example, derived from the GNU C Library 2.5 implementation of mktime (2006-09-09), the code assumes wraparound arithmetic in + to detect signed overflow:

If your code looks like these examples, it is probably safe even though it does not strictly conform to the C standard. This might lead one to believe that one can generally assume wraparound on overflow, but that is not always true, as can be seen in the next section.

Next: Signed Overflow Advice , Previous: Signed Overflow Examples , Up: Overflow   [ Contents ][ Index ]

Compilers sometimes generate code that is incompatible with wraparound integer arithmetic. A simple example is an algebraic simplification: a compiler might translate (i * 2000) / 1000 to i * 2 because it assumes that i * 2000 does not overflow. The translation is not equivalent to the original when overflow occurs: e.g., in the typical case of 32-bit signed two’s complement wraparound int , if i has type int and value 1073742 , the original expression returns -2147483 but the optimized version returns the mathematically correct value 2147484.

More subtly, loop induction optimizations often exploit the undefined behavior of signed overflow. Consider the following contrived function sumc :

To avoid multiplying by 53 each time through the loop, an optimizing compiler might internally transform sumc to the equivalent of the following:

This transformation is allowed by the C standard, but it is invalid for wraparound arithmetic when INT_MAX / 53 < hi , because then the overflow in computing expressions like hi * 53 can cause the expression i <= hi to yield a different value from the transformed expression ic <= hic .

For this reason, compilers that use loop induction and similar techniques often do not support reliable wraparound arithmetic when a loop induction variable like ic is involved. Since loop induction variables are generated by the compiler, and are not visible in the source code, it is not always trivial to say whether the problem affects your code.

Hardly any code actually depends on wraparound arithmetic in cases like these, so in practice these loop induction optimizations are almost always useful. However, edge cases in this area can cause problems. For example:

Here, the loop attempts to iterate through all powers of 2 that int can represent, but the C standard allows a compiler to optimize away the comparison and generate an infinite loop, under the argument that behavior is undefined on overflow. As of this writing this optimization is not done by any production version of GCC with -O2 , but it might be performed by other compilers, or by more aggressive GCC optimization options, and the GCC developers have not decided whether it will continue to work with GCC and -O2 .

Next: Signed Integer Division , Previous: Optimization and Wraparound , Up: Overflow   [ Contents ][ Index ]

Ideally the safest approach is to avoid signed integer overflow entirely. For example, instead of multiplying two signed integers, you can convert them to unsigned integers, multiply the unsigned values, then test whether the result is in signed range.

Rewriting code in this way will be inconvenient, though, particularly if the signed values might be negative. Also, it may hurt performance. Using unsigned arithmetic to check for overflow is particularly painful to do portably and efficiently when dealing with an integer type like uid_t whose width and signedness vary from platform to platform.

Furthermore, many C applications pervasively assume wraparound behavior and typically it is not easy to find and remove all these assumptions. Hence it is often useful to maintain nonstandard code that assumes wraparound on overflow, instead of rewriting the code. The rest of this section attempts to give practical advice for this situation.

If your code wants to detect signed integer overflow in sum = a + b , it is generally safe to use an expression like (sum < a) != (b < 0) .

If your code uses a signed loop index, make sure that the index cannot overflow, along with all signed expressions derived from the index. Here is a contrived example of problematic code with two instances of overflow.

Because of the two overflows, a compiler might optimize away or transform the two comparisons in a way that is incompatible with the wraparound assumption.

If your code uses an expression like (i * 2000) / 1000 and you actually want the multiplication to wrap around on overflow, use unsigned arithmetic to do it, e.g., ((int) (i * 2000u)) / 1000 .

If your code assumes wraparound behavior and you want to insulate it against any GCC optimizations that would fail to support that behavior, you should use GCC ’s -fwrapv option, which causes signed overflow to wrap around reliably (except for division and remainder, as discussed in the next section).

If you need to port to platforms where signed integer overflow does not reliably wrap around (e.g., due to hardware overflow checking, or to highly aggressive optimizations), you should consider debugging with GCC ’s -ftrapv option, which causes signed overflow to raise an exception.

Previous: Signed Overflow Advice , Up: Overflow   [ Contents ][ Index ]

Overflow in signed integer division is not always harmless: for example, on CPUs of the i386 family, dividing INT_MIN by -1 yields a SIGFPE signal which by default terminates the program. Worse, taking the remainder of these two values typically yields the same signal on these CPUs, even though the C standard requires INT_MIN % -1 to yield zero because the expression does not overflow.

Next: Index , Previous: Overflow , Up: Top   [ Contents ][ Index ]

The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”.

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD , and standard-conforming simple HTML , PostScript or PDF designed for human modification. Examples of transparent image formats include PNG , XCF and JPG . Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML , PostScript or PDF produced by some word processors for output purposes only.

The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text.

The “publisher” means any person or entity that distributes copies of the Document to the public.

A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition.

The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

  • Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
  • List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
  • State on the Title page the name of the publisher of the Modified Version, as the publisher.
  • Preserve all the copyright notices of the Document.
  • Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
  • Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
  • Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document’s license notice.
  • Include an unaltered copy of this License.
  • Preserve the section Entitled “History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled “History” in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
  • Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the “History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
  • For any section Entitled “Acknowledgements” or “Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
  • Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
  • Delete any section Entitled “Endorsements”. Such a section may not be included in the Modified Version.
  • Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section.
  • Preserve any Warranty Disclaimers.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles.

You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.”

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/ .

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document.

“Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site.

“CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.

“Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document.

An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.

The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.

ADDENDUM: How to use this License for your documents

To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with…Texts.” line with this:

If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.

If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.

Previous: GNU Free Documentation License , Up: Top   [ Contents ][ Index ]

C++ also has complex number support, but it is incompatible with the ISO C99 types.

a full declarator is a declaration of a function or an object which is not part of another object

However if for example MAX is INT_MAX and x is of type int , we clearly have a problem with overflow. See Overflow .

Rarely, argv[0] can be a null pointer (in this case argc is 0) or argv[0][0] can be the null character. In any case, argv[argc] is a null pointer.

Home » Learn C Programming from Scratch » C Union

Summary : in this tutorial, you’ll learn about a new type called C union and how to use it effectively in your program.

What is a C union?

A structure allows you to define a new data type with multiple related fields. Each field takes up a separate storage location. For example:

The point structure has two fields x-coordinate and y-coordinate. Each takes up a separate space in the memory.

A union is similar to a structure. However, it defines a single location to store values of different fields at a single point in time.

In this quantity union, the i_value and f_value fields share the same memory location.

The following picture illustrates the difference between a structure and a union:

c union vs struct

By definition, a union is a type that stores different values in the same memory location but not at the same time. A union is a group of data objects that share a single block of memory.

C union syntax

The syntax of defining a union is similar to the syntax of defining a structure type. The following illustrates the syntax for defining a union:

In this syntax:

  • First, start with the union keyword followed by the union name.
  • Second, specify the fields with types.

To access a member of a union, you use the ( . ) operator like this :

Union vs. Structure

In a structure , each field stores data separately. If you change the value of one field of a structure, the values of the other fields do not change.

However, in a union, all the fields share the same block of memory. This block of memory is big enough to store the value of the largest field. Smaller members use as much memory as necessary. If you change the value of a field, the values of other fields also change.

If you need to store data in members simultaneously, you need to use a structure .

Initialize a union

C allows you to initialize a union in two ways:

  • Initialize a union by initializing the first member of a union.
  • Or initialize a union by assigning it to another union with the same type.

The following program demonstrates how to initialize a union in both ways.

C Union Example

In this example, we have an account structure that could be personal or business account based on the account_type enumeration . If it is a personal account the info member is associated with the person structure, otherwise, it is associated with the  company structure.

Just take few minutes go through the code to have a better understanding of using the C Union .

In this tutorial, you have learned how to use C union and understand the differences between a union and a structure.

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

' src=

Last Updated on June 19, 2023 by Mayank Dham

c union assignment

In this blog, we’ll learn about union in C with a thorough introduction, the syntax of the union in C, an example of union followed by popper examples of union, accessing union in c member, advantages and disadvantages of union followed by some similarity and distinguishing features between union and structure, all with a thorough explanation from scratch.

What is a Union in C

In the C programming language, a union is a user-defined data type that allows different types of data to be stored in the same memory location. It provides a way to define a variable that may have different data types, but at any given time, only one member of the union can hold a value. The memory allocated for a union is large enough to hold the largest member within it. All members of a union share the same memory space, which means that changing the value of one member will modify the other members as well. This feature is useful when you want to represent different types of data in a compact and efficient manner.

Syntax of the Union in C

We have to use a union keyword for declaring union followed by the name you wanna give to the container. Because enough bytes must be set aside to store the greatest-sized field, the union’s size is equal to the size of its largest field.

A collection of variable values and, optionally, a tag identifying the union are specified in a "union declaration." The "members" of the union, which are the variable values, might be of many sorts. In other languages, "variant records" are comparable to unions.

Above is the example of a general syntax of the union in c that you have to use the keyword named union after that the name of the container and in the container the values of its characteristics and properties.

Create Union Variables

We define a union in c outside the main function and to use a union in c inside the main function we have to create the user-defined variable here we will see the methods to create those user-defined methods as they are known as union variables.

In the above example we have created a union in c with the name of the phone which have two properties named price of the name and the name of the phone. In the main function, we have created the union variables by defining the anime of union first after that the name of the variables that we want to give to the variables we have given phone1 and phone 2 both ar union in c variables but phone 3 is union in c pointer.

We can create a union variable in an alternate way which is explained below:

In the above example we have created union variables in an alternate way as here we have created them along the union in c declaration and not in the main function. Here we do not need to name the union and the name of the container again as we are declaring the union variable along the main union in the c declaration so there will be no need for a declaration. In this case also phone 1 and phone 2 are the union variables whereas phone 3 is a union in c pointer.

Example of Union in C

In this section, we will see the example of the union in c, in the example we will see the proper declaration of union in c with the initialization of union variables and the proper way of accessing union variables in the code.

Code Implementation:

Explanation of the above code In the above example we have created a union in c with the name Example and in that union in c we have an integer value, a float value, and a character array. Now in the main function, we have declared a union variable named example by following the syntax explained above and now we are initializing all the values of the union in c variable by just normal allocation of using the ‘.’ operator and you can see the output in the above image accordingly.

Advantages of Union in C

The union data type in C offers several advantages and use cases. Here are some of the main advantages of using unions:

  • Memory efficiency: Unions allow different data types to share the same memory space. This can be particularly useful when you have a scenario where only one member of the union is active at any given time. By sharing memory, unions can save memory compared to using separate variables for each data type.
  • Versatile representation: Unions provide a way to represent a single value that can take on different data types. This versatility allows you to handle scenarios where a value may need to be interpreted differently based on the context. For example, a union can be used to store a numeric value as either an integer or a floating-point number, depending on the situation.
  • Efficient data manipulation: Unions make it convenient to manipulate and interpret data in different ways. By accessing different members of a union, you can treat the same memory location as different data types, allowing for efficient data conversions and calculations.
  • Compact code: Using unions can result in more compact and readable code, especially in cases where you need to work with multiple data types that are closely related or interchangeable. Rather than declaring separate variables, you can define a single union variable, leading to cleaner and more concise code.
  • Compatibility with external data formats: Unions can be helpful when working with external data formats that have variable interpretations for certain fields. By using unions, you can easily map the different interpretations of a field without the need for extensive data type conversions.

Disadvantages of the Union in C

While unions in C offer advantages in terms of memory efficiency and versatility, they also come with some potential disadvantages. Here are a few of the disadvantages of using unions:

  • Memory interpretation issues: Unions can lead to memory interpretation issues if not used carefully. Since multiple members share the same memory space, accessing a member that is not currently active can result in undefined behavior. It is crucial to keep track of which member is valid at any given time to avoid incorrect interpretation of data.
  • Limited size: Unions can only allocate memory that is large enough to hold the largest member within them. This limitation can be problematic if you need to store data that exceeds the size of the largest member. In such cases, unions may not be suitable, and you might need to consider alternative approaches.
  • Lack of type checking: Unions do not provide built-in type checking mechanisms. It is the programmer’s responsibility to ensure that the correct member is accessed and that the data is interpreted correctly. Without proper handling, type mismatches can lead to unexpected results and bugs that can be challenging to identify and debug.
  • Potential for data loss: If different members of a union store data of different sizes, there is a risk of data loss or truncation. For example, if a union has a member that stores a 32-bit integer and another member that stores an 8-bit character, storing a value that exceeds the range of the character member may result in data loss.
  • Portability concerns: Unions might have portability issues across different platforms and compilers. The representation of data in memory can vary depending on the architecture and compiler implementation. Consequently, code using unions may behave differently on different systems, leading to non-portable code.
  • Code readability and maintainability: While unions can make code more compact, they can also make it less readable and maintainable, especially when used extensively or in complex scenarios. The implicit nature of unions can make it challenging for other developers to understand and modify the code, potentially leading to errors and difficulties in maintenance.

Similarities between Structure and Union

There are many similarities between union in c and structures and in this part we will see some of them.

  • Both union and structure are used to store different types of data in a single unit and they are user-defined data types.
  • Functions may accept a structure or union as a parameter and return it as a parameter. The type of the argument and the function parameter must match. Similar to a scalar variable, a structure or union is supplied by value as the equivalent parameter.
  • Only the assignment = and sizeof operators are supported by unions and structures. The members and member types of the two structures or unions in the assignment must match.
  • To access member variables inside of both user-defined datatypes, use the ‘.’ operator, which has one of the highest precedences.
  • Any object, including other unions, structures, or arrays, may be one of their members. A bit field can also be a part of a member.

Difference between Union and Structure in C

Conclusion In conclusion, unions in the C programming language offer advantages in terms of memory efficiency, versatile data representation, and efficient data manipulation. They can help optimize memory usage by sharing memory space among different data types and provide flexibility when working with varying interpretations of data. However, unions also have disadvantages such as potential memory interpretation issues, lack of type checking, limited size, and potential for data loss. It is crucial to use unions carefully, ensuring proper handling of the active member and appropriate interpretation of data.

Here are a few frequently asked questions (FAQs) related to unions in C:

Q1. Can a union contain members of different sizes? Yes, a union can contain members of different sizes. However, the union will allocate memory that can accommodate the largest member within it. Therefore, if a member requires more memory than the others, the union size will be based on that largest member.

Q2. Can unions be nested within structures or arrays? Yes, unions can be nested within structures or arrays in C. This allows for more complex data structures where different parts may have varying interpretations or data types.

Q3. Can unions be used as function parameters or return types? Yes, unions can be used as function parameters or return types in C. However, it’s essential to carefully manage the active member of the union to ensure correct interpretation and avoid undefined behavior.

Q4. Are there any restrictions on the types of data that can be stored in a union? Unions can store any data type, including built-in types like int, float, char, as well as user-defined structures and enumerations. However, unions cannot contain members that are arrays or functions.

Q5. How can I determine which member of a union is currently active? There is no built-in mechanism in unions to track the active member. It is the programmer’s responsibility to keep track of the active member or use additional variables or flags to indicate the currently valid member.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Null character in c, assignment operator in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c.

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - Functions
  • C - Main Functions
  • C - Return Statement
  • C - Scope Rules
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointer Arithmetics
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

The union keyword in C lets you define a derived data type, very mush similar to the struct keyword. A union data type in C also that allows to store different data types in the consecutive memory location. However, unlike a struct variable, a variable of union type, only one of its members can contain a value at any given time, whereas a struct variable stores values of all the elements.

Defining a Union

To define a union, you must use the union keyword in the same way as you did while defining a structure. The union keyword defines a new data type with more than one member for your program. The format of the union statement is as follows −

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables.

Here is a definition of union type called myunion −

It may be noted that the definition of union is similar to the definition of struct. A definition od struct type mystruct with the same elements looks like this −

The main difference between struct and union is the size of the variables. The compiler allocates the memory to a struct variable, to be able to store values for all the elements. In mystruct, there are three elements one each int, double and char, requiring 13 bytes (4+8+1). Hence,

returns 13.

On the other hand, for a union type variable, the compiler allocates a chunk of memory of the size enough to accommodate the element of largest byte size. The myunion type has an int, double and a char element. Out of which the size of double is the largest − 8. Hence,

Another point to take into consideration, is that a union variable can hold value of only one its elements. When you assign value to one element, the other elements are undefined. If you try to use, it will result in some garbage.

Let us first initialize a mystruct variable −

The memory allocation is done as follows −

On the other hand, when a myunion variable is created, you can either assign value to a, or b or c. Total memory allocated to myunion variable is 8 bytes. If it holds an int, remaining 4 bytes will be unused. If you hold a char, the remaining 7 bytes will be garbage.

Initialize the int element

The other elements become garbage

When a double element is assigned, the entire allocated memory is occupied by u1.b as it is the element with largest size

The entire memory allocated is occupied and there is no garbage deposited.

However, when you assign value to the char element,

In the code below, we define a union type named Data having three members i, f, and str −

Now, a variable of Data type can store an integer, a floating−point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. The following example displays the total memory size occupied by the above union −

When the above code is compiled and executed, it produces the following result −

Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. The following example shows how to use unions in a program −

Here, we can see that the values of i and f members of union shows garbage because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well.

Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions −

Here, all the members are getting printed very well because one member is being used at a time.

C Language Tutorial

c union assignment

Branch & Jump Stmt

Union in c programming.

A union in the C programming language is a special data type that allows different variables to be stored in the same memory location. It is similar to a structure but only one member can hold a value at a time.

The syntax for declaring a union in the C programming language is as follows:

In this example, we define a union called Number with an integer member of type int and a floating_point member of type float . We can assign values to one member and access it, but when we assign a value to another member, the previously stored value becomes invalid.

Note: Using unions requires careful handling to avoid undefined behavior. Make sure to access the currently active member.

Here's an example of union initialization and assignment in the C programming language:

In this code, we define a union called ExampleUnion that has three members: intValue of type int, floatValue of type float, and stringValue of type character array (char[20]).

In the main() function, we demonstrate union initialization and assignment.

First, we initialize the myUnion variable with an initial value of 42 for the intValue member using designated initializer syntax.

Next, we declare the anotherUnion variable and assign a value of 3.14 to the floatValue member.

Finally, we access the union members using dot notation (.) and print their values using printf().

Key Points about Unions in C

  • Union allows different variables to share the same memory location.
  • Only one member of a union can hold a value at a time.
  • Unions provide a way to store different types of data in a single variable.
  • Accessing an inactive member of a union can lead to undefined behavior.
  • The size of a union is determined by the size of its largest member.
  • Unions are useful when you need to manipulate different types of data using the same memory space.
  • Unions can be used for type punning, which allows interpreting the bits of one member as another member's type.
  • Unions can be combined with structures to create complex data structures that can hold different types of values.
  • Unions can be initialized using member-wise initialization or designated initialization.
  • Unions do not provide built-in type checking, so it's the programmer's responsibility to keep track of the currently active member.
  • Unions can be nested within other unions, allowing for hierarchical data representation.
  • Unions can be used for efficient memory utilization and compact storage of data, especially in low-level programming and embedded systems.

Union Size and Memory Layout

Union size and memory layout are related to how memory is allocated and organized for unions in programming languages.

In programming, a union is a special data structure that allows storing different types of data in the same memory location. It enables you to define a single variable that can hold values of different types but only one type at a time. The memory allocated for a union is based on the size of its largest member.

The size of a union is determined by the size of its largest member, as unions are allocated enough memory to accommodate the largest member. For example, if a union has members of types int, char, and float, and the float type has the largest size among these, the size of the union will be equal to the size of a float.

The memory layout of a union depends on the programming language and compiler being used. In most languages, including C and C++, the memory layout of a union is such that all members share the same memory location, and their values overlap. This means that changing the value of one member will affect the values of other members if they share the same memory space.

It's important to note that accessing a member of a union that was not the most recently assigned value may result in undefined behavior, as there's no type-checking within unions to ensure that the correct member is being accessed. Therefore, unions require careful handling to ensure that the correct member is used at any given time.

Here's a C example to illustrate the size and memory layout of a union:

In this example, the Data union has three members: i of type int , c of type char , and f of type float . The size of the Data union will be equal to the size of the largest member, which is float in this case. The memory layout will allow each member to occupy the same memory space, resulting in overlapping values when one member is assigned after another.

As you can see, when a member is assigned, the value of other members might change, as they share the same memory space. It's crucial to keep track of which member is valid at a given time to avoid unintended behavior.

Unions with Structures in C

In this code, we define two structures: struct Rectangle and struct Circle. These structures represent a rectangle with width and height, and a circle with a radius, respectively.

We then define a union called union Shape, which includes the struct Rectangle and struct Circle as its members.

The printShape() function takes an instance of the union Shape as a parameter and determines the shape type by comparing the size of the union with the sizes of the individual structures. It then prints the details of the corresponding shape.

In the main() function, we create an instance of union Shape called shape and assign values to its members. We first assign values to the rectangle member and then call printShape() to print its details. Next, we assign values to the circle member and call printShape() again to print the circle's details.

Enumerated Union in C Programming

To declare an enumerated union, you use the following syntax:.

The enum keyword is used to define the members of the enumerated union. The type keywords are used to specify the data types of the members. The variable name is used to refer to the enumerated union variable.

The following example declares an enumerated union called Color that has three members: RED, GREEN, and BLUE:

The Color enumerated union can be used to store any of the three colors: red, green, or blue. The member member can be used to store the color as an enumerated constant, while the red, green, and blue members can be used to store the color as an integer value.

The following code shows how to use the Color enumerated union:

The code above will print the following output to the console:

This is because the RED enumerated constant has a value of 1.

Enumerated unions can be a useful data structure for storing data that can be represented by a set of named constants. They can also be used to improve the readability and maintainability of your code.

Here's an example of a program using a structure that includes a union for representing colors:

In this program, we define a structure called Color, which includes a union. The union contains an enumeration member member that represents the color (RED, GREEN, or BLUE), and a struct that represents the RGB values (red, green, and blue).

In the main function, we declare a variable color of type union Color. We assign the member of the union as BLUE and then use a switch statement to print the corresponding color name.

Next, we assign specific values to the red, green, and blue members of the union and print them.

Note that when using the struct members of the union, you access them directly without referencing the union's name.

When compiling and running this program, you should see the output:

This demonstrates how you can use a structure with a union to represent different aspects of a color using a common memory location.

Unions and Bit Fields in C

Unions and bit fields are two special data types in C that can be used to save memory and improve performance.

A union is a data type that can store multiple data values of different types in the same memory location. This is useful when you need to store multiple related values, such as the x, y, and z coordinates of a point.

To declare a union in C, you use the following syntax:

A union can only store one value at a time. When you assign a value to a union member, all other members of the union are set to their default values.

A bit field is a data type that can store a single bit of data. This is useful when you need to store small pieces of data, such as flags or Boolean values.

To declare a bit field in C, you use the following syntax:

The bit_field() macro takes two arguments: the number of bits to store and the name of the bit field.

Bit fields are stored in the same memory location as the other members of the struct. The size of the struct is increased by the number of bits specified for each bit field.

Unions and bit fields can be used to save memory and improve performance. However, they should be used with care. Unions can lead to unexpected behavior if you are not careful, and bit fields can be difficult to read and maintain.

Here are some examples of how unions and bit fields can be used:

  • Storing multiple related values: A union can be used to store multiple related values, such as the x, y, and z coordinates of a point. This can save memory, because only one value needs to be stored in memory at a time.
  • Storing small pieces of data: Bit fields can be used to store small pieces of data, such as flags or Boolean values. This can save memory, because only the bits that are needed are stored.
  • Improving performance: Unions and bit fields can be used to improve performance by reducing the number of memory accesses. For example, if you need to store a large number of flags, you can use a bit field to store each flag in a single bit. This can improve performance, because fewer memory accesses are required to read or write the flags.

Unions and bit fields should not be used when:

  • You need to store large amounts of data.
  • You need to store data that is not related.
  • You need to store data that is not fixed in size.
  • You need to be able to read or write data in a random order.

Bit Fields Example in C

Bit fields allow you to allocate specific numbers of bits within a structure to store data. This feature is useful when you want to optimize memory usage or manipulate individual bits of data. You can specify the number of bits each member should occupy within the structure.

Here's an example of a structure with bit fields:

Type checking and error handling with unions in c.

In the C programming language, unions provide a way to define a type that can hold different types of data, but only one at a time. When using unions, type checking and error handling can be a bit more challenging compared to structures or individual variables because the type of data stored in a union is not explicitly tracked.

Tagged Union (Discriminated Union)

One common approach is to use a tagged union, also known as a discriminated union. This involves adding an additional field to the union, commonly called a tag, that specifies the type of data currently stored. For example:

Convention-based approach

Another approach is to establish a convention for using the union, where you rely on some external mechanism (such as comments or naming conventions) to indicate the type of data stored. This approach is less robust because it relies on developers following the convention correctly and lacks the built-in type checking provided by the tagged union approach.

Error Handling

Error handling with unions can be challenging because accessing the wrong member of a union can lead to undefined behavior. It's important to ensure that you always access the correct member based on the current type.

One way to handle errors is by using assertions or conditionals to verify the current type before accessing a specific member:

You can also consider using enums or error codes to indicate and handle errors related to unions in a more structured way.

Remember that unions in C provide flexibility but also require careful handling to avoid errors. It's important to establish clear conventions or use a tagged union approach to ensure type checking and handle errors appropriately.

  • Learn C Language
  • Learn C++ Language
  • Learn python Lang

C Programming Tutorial

  • Union Basics in C

Last updated on July 27, 2020

Let's say you are creating a program to record the name and quantity of different goods, where quantity might be count, weight or volume. One way to approach the problem is to create structure as follows:

As we know balls quantity is measured using count. So, in this case, there is no need for weight and volume.

Similarly in the following statement:

As the quantity of flour is measured using weight. So, in this case, there is no need to store count and volume.

From these observations, we can conclude that, a particular type of goods at a time can be measured using only one of the quantity either a count or a weight or a volume.

At this point our program has following limitations:

  • It takes more space than required, hence less efficient.
  • Someone might set more than one value.

It would be much more useful if we could record quantity using either a count, a weight, or a volume. That way we can save a lot of memory.

In C, a union allows us to do just that.

What is a Union? #

Like structures, unions are used to create new data types. It can also contain members just like structures. The syntax of defining a union, creating union variables and accessing members of the union is same as that of structures, the only difference is that union keyword is used instead of structure .

The important difference between structures and unions is that in structures each member has it's own memory whereas members in unions share the same memory. When a variable of type union is declared the compiler allocates memory sufficient to hold the largest member of the union. Since all members share the same memory you can only use one member of a union at a time, thus union is used to save memory. The syntax of declaring a union is as follows:

Just like structure you can declare union variable with union definition or separately.

If we have a union variable then we can access members of union using dot operator ( . ) , similarly if we have pointer to union then we can access members of union using arrow operator ( -> ) .

The following program demonstrates how to use a union.

Expected Output:

How it works:

In lines 7-12, a union data is declared with three members namely var1 of type int , var2 of type double and var3 of type char . When the compiler sees the definition of union it will allocate sufficient memory to hold the largest member of the union. In this case, the largest member is double , so it will allocate 8 bytes of memory. If the above definition would have been declared as a structure, the compiler would have allocated 13 bytes ( 8+4+2 ) of memory (here we are ignoring holes, click here to learn more about it).

In line 16, a union variable t of type union data is declared.

In line 18, the first member of t i.e var1 is initialized with a value of 10 . The important thing to note is that at this point the other two members contain garbage values.

In line 19, the value of t.var1 is printed using the printf() statement.

In line 21, the second member of t i.e var2 is assigned a value of 20.34 . At this point, the other two members contain garbage values.

In line 22, the value of t.var2 is printed using printf() statement.

In line 24, the third member of t i.e var3 is assigned a value of 'a' . At this point, the other two members contain garbage values.

In line 25, the value of t.var3 is printed using printf() statement.

In line 27, the sizeof() operator is used to print the size of the union. Since we know that, in the case of a union, the compiler allocates sufficient memory to hold the largest member. The largest member of union data is var2 so the sizeof() operator returns 8 bytes which is then printed using the printf() statement.

Initializing Union Variable #

In the above program, we have seen how we can initialize individual members of a union variable. We can also initialize the union variable at the time of declaration, but there is a limitation. Since union share same memory all the members can't hold the values simultaneously. So we can only initialize one of the members of the union at the time of declaration and this privilege goes to the first member. For example:

This statement initializes the union variable j or in other words, it initializes only the first member of the union variable j .

Designated initializer #

Designated initializer allows us to set the value of a member other than the first member of the union. Let's say we want to initialize the var2 member of union data at the time of declaration. Here is how we can do it.

This will set the value of var2 to 9.14 . Similarly, we can initialize the value of the third member at the time of declaration.

The following program demonstrates the difference between a structure and a pointer.

In lines 6-11, a structure of type s is declared with three members namely var1 of type int , var2 of type float and var3 of type char .

In line 13-18, a union of type u is declared with three members namely var1 of type int , var2 of type float and var3 of type char .

In line 22 and 23 declares a structure variable a of type struct s and union variable b of type union u respectively.

In line 27, the address of structure variable a is printed using & operator.

In line 28, the size of structure variable is printed using sizeof() operator.

Similarly the printf() statements in line 38 and 39 prints address and size of union variable b respectively.

All the member of a union shares the same memory that's why the next three printf() statements prints the same address.

c union assignment

Notice that the members of the union share the same address while the members of structure don't. The difference in size of structure and union variable also suggests that in some cases union may provide a more economical use of memory. Another important point I want to emphasise is that size of the structure may be greater than the sum of members due to the boundary alignment discussed earlier, the same thing is true for unions.

A structure can be a member one of the union. Similarly, a union can be a member of the structure.

Let's now shift our attention back to the problem we discussed while introducing unions.

After learning about unions we know that at a time only one member of union variable will be usable, that means the union is perfect for defining quantity. So instead if storing different quantity as members of structure why not create a union of a quantity that way for any goods only one member of the union will be usable.

Instead of nesting union quantity we can define it outside the goods structure.

If we want to access the value of count we can write:

Similarly to access the value of weight we can write:

The following program demonstrates how we can use a union as a member of the structure.

In lines 7-12, a union quantity is declared with three members namely count of type int , weight of type float and volume of type float .

In lines 14-18, structure goods is declared with 2 members namely name which is an array of characters and w of type union quantity.

In line 22, structure variable g1 is declared and initialized. The important thing to note how designated initializer is used to initialize the weight member of the union. If we would have wanted to initialize the first element, we would have done it like this:

In line 23, structure variable g2 is declared and initialized.

In line 25 and 26, name and weight of the first goods is printed using printf() statement.

Similarly in line 28 and 29, name and weight of the second goods is printed using printf() statement.

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • AI Prolog Installation in Turbo C++
  • Signal Handling in C++
  • Cross-platform Windows / Raspberry Pi project with C++, OpenCV and Gtk
  • Strict Type Checking in C++
  • is_void template in C++
  • Introduction to Complex Objects and Composition
  • How to quickly swap two arrays of same size in C++?
  • OpenCV C++ Windows Setup using Visual Studio 2019
  • Copy Constructor vs Assignment Operator in C++
  • random header in C++ | Set 3 (Distributions)
  • Is assignment operator inherited?
  • C++ Installation on MacBook M1 for VS Code
  • wcslen() function in C++ with Examples
  • Fork CPP | Course Structure
  • RAPTOR Tool - A Flowchart Interpreter
  • Nested Classes in C++
  • Representation of Int Variable in Memory in C++
  • Local Classes in C++
  • Application of OOPs in C++

In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable. The size of the union is equal to the size of the largest data type.

Memory space can be used by one member variable at one point in time, which means if we assign value to one member variable, it will automatically deallocate the other member variable stored in the memory which will lead to loss of data.

Need of Union in C++

  • When the available memory is limited, it can be used to achieve memory efficiency.
  • It is used to encapsulate different types of data members.
  • It helps in optimizing the performance of applications.

Syntax of Union in C++

Union is defined using the ‘union’ keyword.

After defining the union we can also create an instance of it the same as we create an object of the class or declare any other data type.

Example of Union in C++

We have not assigned the values to all data members in one go as we do normally because they share the same memory location and if we do so then their value will be overwritten.

C++ Program to Illustrate that Data Members of Union Share Same Memory Location

In the below example, we are verifying that is it actually data members of the union are sharing the same memory or not.

Explanation

First, we have defined a union and defined three different data members inside it. After that, in the main function, we have defined a union variable. Now, we have printed the address of all data members of the union using the reference operator ‘&’.

We can see in the output that the addresses of all three data members are the same which proves that members of the union shared the same memory. We have also printed the size of a union which is ‘8’ because double takes 8 bytes and it largest among int, float, and double.

Anonymous Unions in C++

Just like anonymous objects we also have anonymous unions in C++ that are declared without any name inside a main function. As we do not define any union variable we can directly access the data members of the union that is why their data members must be declared with unique names to avoid ambiguity in the current scope.

In the main function, we have defined an anonymous without defining any variable. After that, we assigned value to data members of a union and print them.

Union-like Classes in C++

A union-like class is just a class with at least one anonymous union defined inside it and the data members defined in an anonymous union are known as variant members .

Example: C++ program to illustrate Union-like classes

In the above example, we have created a class ‘student’ a data member, and an anonymous union inside it which is called a union-like class. After that, we created an object for student class ‘s1’ using which we can access the data member of the student class and anonymous union members. So, using object ‘s1’ we assign values to class data members and union data members and then print their values.

Please Login to comment...

author

  • 10 Best Free Social Media Management and Marketing Apps for Android - 2024
  • 10 Best Customer Database Software of 2024
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

2018 Primetime Emmy & James Beard Award Winner

R&K Insider

Join our newsletter to get exclusives on where our correspondents travel, what they eat, where they stay. Free to sign up.

A History of Moscow in 13 Dishes

Featured city guides.

  • Share full article

Advertisement

Supported by

The A.C.L.U. Said a Worker Used Racist Tropes and Fired Her. But Did She?

The civil liberties group is defending itself in an unusual case that weighs what kind of language may be evidence of bias against Black people.

The facade of the A.C.L.U. building in Washington.

By Jeremy W. Peters

Kate Oh was no one’s idea of a get-along-to-go-along employee.

During her five years as a lawyer for the American Civil Liberties Union, she was an unsparing critic of her superiors, known for sending long, blistering emails to human resources complaining about what she described as a hostile workplace.

She considered herself a whistle blower and advocate for other women in the office, drawing unflattering attention to an environment she said was rife with sexism, burdened by unmanageable workloads and stymied by a fear-based culture.

Then the tables turned, and Ms. Oh was the one slapped with an accusation of serious misconduct. The A.C.L.U. said her complaints about several superiors — all of whom were Black — used “racist stereotypes.” She was fired in May 2022.

The A.C.L.U. acknowledges that Ms. Oh, who is Korean American, never used any kind of racial slur. But the group says that her use of certain phrases and words demonstrated a pattern of willful anti-Black animus.

In one instance, according to court documents, she told a Black superior that she was “afraid” to talk with him. In another, she told a manager that their conversation was “chastising.” And in a meeting, she repeated a satirical phrase likening her bosses’ behavior to suffering “beatings.”

Did her language add up to racism? Or was she just speaking harshly about bosses who happened to be Black? That question is the subject of an unusual unfair-labor-practice case brought against the A.C.L.U. by the National Labor Relations Board, which has accused the organization of retaliating against Ms. Oh.

A trial in the case wrapped up this week in Washington, and a judge is expected to decide in the next few months whether the A.C.L.U. was justified in terminating her.

If the A.C.L.U. loses, it could be ordered to reinstate her or pay restitution.

The heart of the A.C.L.U.’s defense — arguing for an expansive definition of what constitutes racist or racially coded speech — has struck some labor and free-speech lawyers as peculiar, since the organization has traditionally protected the right to free expression, operating on the principle that it may not like what someone says, but will fight for the right to say it.

The case raises some intriguing questions about the wide swath of employee behavior and speech that labor law protects — and how the nation’s pre-eminent civil rights organization finds itself on the opposite side of that law, arguing that those protections should not apply to its former employee.

A lawyer representing the A.C.L.U., Ken Margolis, said during a legal proceeding last year that it was irrelevant whether Ms. Oh bore no racist ill will. All that mattered, he said, was that her Black colleagues were offended and injured.

“We’re not here to prove anything other than the impact of her actions was very real — that she caused harm,” Mr. Margolis said, according to a transcript of his remarks. “She caused serious harm to Black members of the A.C.L.U. community.”

Rick Bialczak, the lawyer who represents Ms. Oh through her union, responded sarcastically, saying he wanted to congratulate Mr. Margolis for making an exhaustive presentation of the A.C.L.U.'s evidence: three interactions Ms. Oh had with colleagues that were reported to human resources.

“I would note, and commend Ken, for spending 40 minutes explaining why three discreet comments over a multi-month period of time constitutes serious harm to the A.C.L.U. members, Black employees,” he said.

Yes, she had complained about Black supervisors, Mr. Bialczak acknowledged. But her direct boss and that boss’s boss were Black.

“Those were her supervisors,” he said. “If she has complaints about her supervision, who is she supposed to complain about?”

Ms. Oh declined to comment for this article, citing the ongoing case.

The A.C.L.U. has a history of representing groups that liberals revile. This week, it argued in the Supreme Court on behalf of the National Rifle Association in a First Amendment case.

But to critics of the A.C.L.U., Ms. Oh’s case is a sign of how far the group has strayed from its core mission — defending free speech — and has instead aligned itself with a progressive politics that is intensely focused on identity.

“Much of our work today,” as it explains on its website, “is focused on equality for people of color, women, gay and transgender people, prisoners, immigrants, and people with disabilities.”

And since the beginning of the Trump administration, the organization has taken up partisan causes it might have avoided in the past, like running an advertisement to support Stacey Abrams’s 2018 campaign for governor of Georgia.

“They radically expanded and raised so much more money — hundreds of millions of dollars — from leftist donors who were desperate to push back on the scary excesses of the Trump administration,” said Lara Bazelon, a law professor at the University of San Francisco who has been critical of the A.C.L.U. “And they hired people with a lot of extremely strong views about race and workplace rules. And in the process, they themselves veered into a place of excess.”

“I scour the record for any evidence that this Asian woman is a racist,” Ms. Bazelon added, “and I don’t find any.”

The beginning of the end for Ms. Oh, who worked in the A.C.L.U.’s political advocacy department, started in late February 2022, according to court papers and interviews with lawyers and others familiar with the case.

The A.C.L.U. was hosting a virtual organization-wide meeting under heavy circumstances. The national political director, who was Black, had suddenly departed following multiple complaints about his abrasive treatment of subordinates. Ms. Oh, who was one of the employees who had complained, spoke up during the meeting to declare herself skeptical that conditions would actually improve.

“Why shouldn’t we simply expect that ‘the beatings will continue until morale improves,’” she said in a Zoom group chat, invoking a well-known phrase that is printed and sold on T-shirts, usually accompanied by the skull and crossbones of a pirate flag. She explained that she was being “definitely metaphorical.”

Soon after, Ms. Oh heard from the A.C.L.U. manager overseeing its equity and inclusion efforts, Amber Hikes, who cautioned Ms. Oh about her language. Ms. Oh’s comment was “dangerous and damaging,” Ms. Hikes warned, because she seemed to suggest the former supervisor physically assaulted her.

“Please consider the very real impact of that kind of violent language in the workplace,” Ms. Hikes wrote in an email.

Ms. Oh acknowledged she had been wrong and apologized.

Over the next several weeks, senior managers documented other instances in which they said Ms. Oh mistreated Black employees.

In early March, Ben Needham, who had succeeded the recently departed national political director, reported that Ms. Oh called her direct supervisor, a Black woman, a liar. According to his account, he asked Ms. Oh why she hadn’t complained earlier.

She responded that she was “afraid” to talk to him.

“As a Black male, language like ‘afraid’ generally is code word for me,” Mr. Needham wrote in an email to other A.C.L.U. managers. “It is triggering for me.”

Mr. Needham, who is gay and grew up in the Deep South, said in an interview that as a child, “I was taught that I’m a danger.”

To hear someone say they’re afraid of him, he added, is like saying, “These are the people we should be scared of.”

Ms. Oh and her lawyers have cited her own past: As a survivor of domestic abuse, she was particularly sensitive to tense interactions with male colleagues. She said she was troubled by Mr. Needham’s once referring to his predecessor as a “friend,” since she was one of the employees who had criticized him.

Mr. Needham said he had been speaking only about their relationship in a professional context.

According to court records, the A.C.L.U. conducted an internal investigation into whether Ms. Oh had any reason to fear talking to Mr. Needham, and concluded there were “no persuasive grounds” for her concerns.

The following month, Ms. Hikes, the head of equity and inclusion, wrote to Ms. Oh, documenting a third incident — her own.

“Calling my check-in ‘chastising’ or ‘reprimanding’ feels like a willful mischaracterization in order to continue the stream of anti-Black rhetoric you’ve been using throughout the organization,” Ms. Hikes wrote in an email.

“I’m hopeful you’ll consider the lived experiences and feelings of those you work with,” she added. (Citing the ongoing case, the A.C.L.U. said Ms. Hikes was unable to comment for this article.)

The final straw leading to Ms. Oh’s termination, the organization said, came in late April, when she wrote on Twitter that she was “physically repulsed” having to work for “incompetent/abusive bosses.”

As caustic as her post was — likely grounds for dismissal in most circumstances — her speech may have been protected. The N.L.R.B.’s complaint rests on an argument that Ms. Oh, as an employee who had previously complained about workplace conditions with other colleagues, was engaging in what is known legally as “protected concerted activity.”

“The public nature of her speech doesn’t deprive it of N.L.R.A. protection,” said Charlotte Garden, a law professor at the University of Minnesota, referring to the National Labor Relations Act, which covers worker’s rights.

She added that the burden of proof rests with the N.L.R.B., which must convince the judge that Ms. Oh’s social media post, and her other comments, were part of a pattern of speaking out at work.

“You could say this is an outgrowth of that, and therefore is protected,” she said.

The A.C.L.U. has argued that it has a right to maintain a civil workplace, just as Ms. Oh has a right to speak out. And it has not retreated from its contention that her language was harmful to Black colleagues, even if her words were not explicitly racist.

Terence Dougherty, the general counsel, said in an interview that standards of workplace conduct in 2024 have shifted, likening the case to someone who used the wrong pronouns in addressing a transgender colleague.

“There’s nuance to the language,” Mr. Dougherty said, “that does really have an impact on feelings of belonging in the workplace.”

Jeremy W. Peters is a Times reporter who covers debates over free expression and how they impact higher education and other vital American institutions. More about Jeremy W. Peters

c union assignment

CNN Politics

A collection of all cnn's political podcasts, featuring episodes from: the assignment with audie cornish, cnn inside politics, cnn political briefing, the axe files, state of the union, cnn one thing and more..

c union assignment

Back to episodes list

When James Carville criticized the “preachy females” at the forefront of Democratic politics, he kicked off a firestorm of outrage and perhaps a little introspection. Did “The Ragin’ Cajun” have a point, however impolitely made? Do Democrats have a problem with men? Especially Black men and other men of color? Jamil Smith is an award-winning writer and the new editor-in-chief of The Emancipator , a nonprofit newsroom run by the Center for Antiracist Research at Boston University, co-founded by Dr. Ibram X. Kendi.

Learn more about your ad choices. Visit podcastchoices.com/adchoices

Baseball players' union head Tony Clark nearly doubled pay to $4.25 million last year

NEW YORK — Baseball players’ association head Tony Clark nearly doubled his pay to $4.25 million in 2023, according the union’s annual federal disclosure filing Monday.

Clark’s income had risen from just under $2 million in his first full year after succeeding Michael Weiner as executive director in 2014 to $2.25 million annually from 2019-2022.

The union said Clark’s salary was $3.25 million and his 2023 income included a $1 million bonus that followed collective bargaining. The players’ association said it thought that bonus was similar to what other major league union executive directors received.

Clark has a $17.95 million, five-year contract that includes salaries of $3.41 million this year, $3.58 million in 2025, $3.76 million in 2026 and $3.95 million in 2027, according to a financial statement by Mazars that also was filed Monday.

The disclosure of this raise came roughly two years after Clark oversaw a lockout that ended with a new collective bargaining agreement and about two weeks after lawyer Harry Marino attempted to rally players and oust Clark’s No. 2, chief negotiator Bruce Meyer. Marino’s critiques include mismanagement of MLBPA funds.

The players last week appeared to reject Marino's insurgency . Clark said the executive subcommittee authorized him to release a statement saying: “We still have issues to discuss, but one thing clear among the MLB executive subcommittee members is that this is no longer a Harry Marino discussion, in any respect.”

Marino earned $215,993 in 2023 before leaving the union last July. After helping minor league players unionize, Marino joined the MLBPA staff in September 2022 and earned $68,977 during the remainder of the year.

Meyer increased his pay to $1.55 million from $1.36 million in 2022, when he was promoted in July to deputy executive director from senior director of collective bargaining and legal . He has a five-year contract for $7.8 million that includes salaries of $1.5 million last year, $1.53 million this year, $1.56 million in 2025, $1,592,000 in 2026 and $1,624,000 in 2027. His agreement may be terminated by either side with 90 days’ notice and by the union at any time for cause.

DeMaurice Smith, executive director of the NFL Players Association, earned roughly $9.3 million in the year ending Feb. 28, 2023, then left last summer. Tamika Tremaglio, executive director of the National Basketball Players Association before resigning in November, made $3.1 million in the year ending Sept. 30.

Total MLBPA spending on employees rose to $16.6 million last year from $15.4 million in 2022 and $11.9 million in 2021.

General counsel Matt Nussbaum earned $866,168 and deputy general counsel Jeff Perconte $681,330. Senior adviser Ian Penny, who had been general counsel until July 2022, earned $834,404 and chief operating officer Xavier James $662,952.

Former players listed include Chris Capuano, senior director of operation ($432,625), and Dave Winfield, a special adviser to Clark ($367,500). Other former players are special assistants Mike Myers ($278,319), Steve Rogers ($276,775), Phil Bradley ($246,206), Rick Helling ($217,324) and Bobby Bonilla ($132,477).

Jeffrey Hammonds, associate director player programs and initiatives, was at $25,884.

As part of its disclosure, the union filed its revised constitution , which specifies 38 executive board seats are held by major leaguers and 34 by minor leaguers.

The union paid $427,484 in rent for its Arizona office, whose opening was announced in February 2023. Rent for the main office in New York totaled $2,085,336.

The accompanying financial statement says the union signed a 15-year lease in December for a new office space it estimates it will move to in October with a five-year extension possible. The union’s rent obligations for all leases will rise from $2.3 million in 2024 to $3.7 million in 2028.

AP MLB: https://apnews.com/hub/mlb

c union assignment

Starbucks violated labor law by barring pro-union buttons, DC Circuit rules

Buttons showing support for a Starbucks Union are seen at the Workers United, an affiliate of the Service Employees International Union, offices in Buffalo, New York

  • Manager's warning wasn't limited to giving customers buttons, court says
  • Dissenting judge said workers could still pass out buttons in private areas
  • Starbucks, union have agreed to 'framework' to guide nationwide organizing

Jumpstart your morning with the latest legal news delivered straight to your inbox from The Daily Docket newsletter. Sign up here.

Reporting by Daniel Wiessner in Albany, New York

Our Standards: The Thomson Reuters Trust Principles. , opens new tab

c union assignment

Thomson Reuters

Dan Wiessner (@danwiessner) reports on labor and employment and immigration law, including litigation and policy making. He can be reached at [email protected].

Read Next / Editor's Picks

United States Supreme Court overturns the landmark Roe v Wade abortion decision

Industry Insight

c union assignment

Mike Scarcella, David Thomas

c union assignment

Karen Sloan

c union assignment

Henry Engler

c union assignment

Diana Novak Jones

Brewers send C Eric Haase outright to Triple-A Nashville after he clears waivers

Milwaukee Brewers catcher Eric Haase looks to place the tag as Los Angeles Dodgers' James Outman is caught out stealing home during the third inning of a spring training baseball game, Saturday, March 2, 2024, in Phoenix. (AP Photo/Carolyn Kaster)

  • Show more sharing options
  • Copy Link URL Copied!

Catcher Eric Haase cleared waivers and is heading to the Milwaukee Brewers’ Triple-A affiliate in Nashville.

The Brewers announced Monday that Haase had been sent outright to Nashville. The 31-year-old Haase was designated for assignment Thursday.

Although Haase batted .395 with a .465 on-base percentage, five homers and 14 RBIs in 18 Cactus League games, he was unable to make the Brewers’ season-opening roster.

Haase signed with the Brewers in December after hitting .201 with four homers and 26 RBIs in 89 games with the Detroit Tigers and Cleveland Guardians last year. Two months after signing Haase, the Brewers also added two-time All-Star catcher Gary Sánchez, who hit .217 with 19 homers in 75 games for the New York Mets and San Diego Padres last season.

Although Haase batted .395 with a .465 on-base percentage, five homers and 14 RBIs in 18 Cactus League games, the Brewers decided against including three catchers on their season-opening roster and selected Sánchez as the lone backup for William Contreras.

AP MLB: https://apnews.com/hub/mlb

Sign up for U-T Sports daily newsletter

The latest Padres, Chargers and Aztecs headlines along with the other top San Diego sports stories every morning.

You may occasionally receive promotional content from the San Diego Union-Tribune.

More in this section

Southern California guard JuJu Watkins looks on before a Sweet 16 college basketball game against Baylor in the women's NCAA Tournament, Saturday, March 30, 2024, in Portland, Ore. Southern California won 74-70. (AP Photo/Howard Lao)

National Sports

JuJu Watkins gets a taste of Mach Madness, and wants more next season

USC freshman JuJu Watkins’ NCAA Tournament run is over, but she’s got plenty to build on

Seattle Kraken center Yanni Gourde, middle right, reaches for the puck against San Jose Sharks defenseman Calen Addison, from left, goaltender Mackenzie Blackwood, middle left, and center Nico Sturm (7) during the third period of an NHL hockey game in San Jose, Calif., Monday, April 1, 2024. (AP Photo/Jeff Chiu)

Bjorkstrand has goal, assist as Kraken beat Sharks 4-2

Oliver Bjorkstrand scored his 20th goal of the season and added an assist as the Seattle Kraken beat the San Jose Sharks 4-2

FILE - LSU head coach Ed Orgeron, left, celebrates with running back Derrius Guice (5) following a win over Mississippi in an NCAA college football game Oct. 21, 2017, in Oxford, Miss. LSU and 10 former students who sued the school over alleged mishandling of sexual assault and domestic violence complaints against football players and others at Louisiana’s flagship state university have settled the case, a judge wrote in a March 28, 2024, order. Four of the the plaintiffs in the 2021 civil case accused former star running back Guice of sexual misconduct. (AP Photo/Rogelio V. Solis, File)

LSU settles case involving sexual assault, domestic violence allegations against football players

LSU and 10 former students who sued the school over alleged mishandling of sexual assault and domestic violence complaints against football players and others at Louisiana’s flagship state university have settled the case

Los Angeles Dodgers' Teoscar Hernandez (37) celebrates his three-run home run with Max Muncy (13) and Freddie Freeman during the sixth inning of a baseball game against the San Francisco Giants, Monday, April 1, 2024, in Los Angeles. Max Muncy and Freddie Freeman also scored. (AP Photo/Ryan Sun)

Freddie Freeman, Teoscar Hernández power Dodgers to 8-3 victory over Giants

Freddie Freeman had three hits, Teoscar Hernández homered for the second straight game and the Dodgers defeated the San Francisco Giants 8-3 Monday night

New York Yankees pitcher Luis Gil reacts after being taken out in the fifth inning during a baseball game against the Arizona Diamondbacks, Monday, April 1, 2024, in Phoenix. (AP Photo/Rick Scuteri)

Yankees earn first 5-game winning streak to start season since 1992, knock off Diamondbacks 5-2

Luis Gil had a successful outing in his return from Tommy John surgery and the New York Yankees started the season on a five-game winning streak for the first time in 32 years, beating the Arizona Diamondbacks 5-2

St. Louis Cardinals starting pitcher Kyle Gibson delivers during the seventh inning of a baseball game against the San Diego Padres, Monday, April 1, 2024, in San Diego. (AP Photo/Denis Poroy)

Contreras, Donovan homer, Gibson dominates as the Cardinals beat Schildt’s Padres 6-2

Willson Contreras and Brendan Donovan each hit a two-run home run, Kyle Gibson was dominant in his St. Louis debut and the Cardinals won 6-2 against their former manager Mike Schildt and the San Diego Padres

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • Personal Finance
  • AP Buyline Personal Finance
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • March Madness
  • AP Top 25 Poll
  • Movie reviews
  • Book reviews
  • Personal finance
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

Microsoft splits Teams from Office after antitrust scrutiny

FILE - The Microsoft logo is pictured outside the headquarters in Paris, on Jan. 8, 2021. Microsoft will stop packaging its Teams videoconferencing app with its Office software after the practice attracted antitrust scrutiny. The tech giant said Monday, April 1, 2024, that customers buying Office subscriptions starting this week won't get Teams bundled with the service. Microsoft will start selling the two products separately around the world, following a move last year to separate the products in Europe. (AP Photo/Thibault Camus, File)

FILE - The Microsoft logo is pictured outside the headquarters in Paris, on Jan. 8, 2021. Microsoft will stop packaging its Teams videoconferencing app with its Office software after the practice attracted antitrust scrutiny. The tech giant said Monday, April 1, 2024, that customers buying Office subscriptions starting this week won’t get Teams bundled with the service. Microsoft will start selling the two products separately around the world, following a move last year to separate the products in Europe. (AP Photo/Thibault Camus, File)

  • Copy Link copied

REDMOND, Wash. (AP) — Microsoft will stop packaging its Teams videoconferencing app with its Office software after the practice attracted antitrust scrutiny.

The tech giant said Monday that customers buying Office subscriptions starting this week won’t get Teams bundled with the service. Microsoft will start selling the two products separately around the world, following a move last year to separate the products in Europe.

That was after the European Union’s executive commission, the 27-nation bloc’s top competition enforcer, opened a formal investigation over concerns that bundling Teams with Office gives the company an unfair edge over competitors.

The investigation was triggered by a complaint filed in 2020 by Slack Technologies, a maker of popular workplace messaging software.

Slack, owned by business software maker Salesforce, alleged that Microsoft was abusing its market dominance to eliminate competition — in violation of EU laws — by illegally combining Teams with its Office suite, which includes Word, Excel and Outlook.

c union assignment

StarTribune

The first new foods to find for the twins 2024 season.

Spring is here for real this time as we gear up for that first crack of the bat to echo through Target Field, home of the Minnesota Twins. We're preparing for Thursday's season opener against the Cleveland Guardians by tasting all the food that pairs well with cheering on a Twins win.

The Twins, in conjunction with food-service partner Delaware North, announced their lineup of new food and drink items. Prices weren't immediately available.

Union Hmong Kitchen Banh Mi Brats are prepped for guests during a tour of the new food for 2024 at Target Field in Minneapolis on Monday.

Bành Mí Brat from Union Hmong Kitchen

Chef Yia Vang continues his path to total food world domination with the genius combination of his Hmong sausage made by Kramarczuk's served in a hot dog bun with bright bành mí accoutrements of pickled vegetables and garlic aioli. We didn't know it was time for an update to the classic ballpark brat, but Vang sure did. Section 127

Smashed Baked Potato seen during a tour of the new food for 2024 at Target Field.

Smashed Baked Potato

Exactly as the name implies, it's a mall food court throwback designed to please our meat-and-potatoes Midwestern ways. Choose your own toppings, but don't skimp on the beer cheese and chopped brisket. Section 117

Parcelle’s C.R.E.A.M. Smoothie, left, and BluePrint Smoothie seen during a tour of the new food for 2024 at Target Field.

C.R.E.A.M. and BluePrint Smoothies from Parcelle

This brand-spanking-new health food eatery in northeast Minneapolis makes a rapid leap to Target Field with two of its signature smoothies packed with fruit, coconut milk and collagen peptides. Our favorite was the strawberry-banana C.R.E.A.M.; close your eyes and you're sipping a beachside cocktail. Section 126 Market

The Walleye Burger from Lord Fletcher’s is seen during a tour of the new food for 2024 at Target Field.

Walleye Burger from Lord Fletcher's

As fresh and fun as casting a line off the dock, Lake Minnetonka staple Lord Fletcher's brings a taste of summer to the heart of Target Field. Coarsely chopped walleye is formed into a burger that's griddled up and served with a punchy burst of lemony tartar sauce on a softly toasted bun. Gate 34

S’mores Boozy Ice Cream is seen during a tour of the new food for 2024 at Target Field.

S'mores Boozy Ice Cream

We didn't think there was any way to improve on classic soft-serve ice cream, but then someone decided to put vodka on it, and we're on board. A toasted marshmallow syrup laced with high-octane alcohol gets drizzled over chocolate and vanilla twist. The sundae is garnished with a marshmallow and a graham cracker. Gate 34

Official Fried Chicken Mighty Buffalo Dry Rub Wings are seen during a tour of the new food for 2024 at Target Field.

Mighty Buffalo Dry Rub Wings from Official Fried Chicken

Pressure-fried chicken wings join the lineup at this year-old stand designed to look and function like an automat. Their crispy breading is tossed with OFC's Buffalo dry rub, which gives them a fiery kick without leaving you with saucy fingers. Ranch is on the side for dipping. (Also new on OFC's menu this year is peppery mac and cheese.) Section 134

Bussin Biria Tacos from Hrbek’s seen during a tour of the new food for 2024 at Target Field.

Bussin Birria Tacos at Hrbek's

From the Mall of America to the outfield, entrepreneur Amol Dixit has brought his Bussin Birria tacos into Minneapolis. Tacos are stuffed with slow-braised beef and cheese, folded and given a quick crisping on the griddle before being served alongside a cup of the dish's signature beef consommé for dipping. Section 114

O’Shaughnessy Distilling Co. cocktails Irish Mojito, from left, Cherry Smashed Whiskey and Vanilla Creamed Whiskey are seen at Keeper’s Heart Town Ball Tavern during a tour of the new food for 2024 at Target Field.

Cherry Smashed Whiskey at Keeper's Heart Town Ball Tavern

The Level 2 pub has been renamed for the local whiskey brand, and three new cocktails from O'Shaughnessy Distilling Co. have landed on its menu. We'll skip the Irish Mojito and Vanilla Creamed Whiskey and go straight for this hot pink bourbon-and-cherry deal, made with Keeper's Heart bourbon, Monin HomeCrafted Cherry Smash, soda and lime. Section 229

Burger Fries from Two Mixed Up seen during a tour of the new food for 2024 at Target Field.

Burger Fries from Two Mixed Up at Thrivent Club

The food hall stand that began by streaming their eats on Twitch are now at the ballfield with three offerings. Like a deconstructed drive-thru order, Burger Fries are the kind of decadence we love to eat in the stands. Battered fries with Philly cheesesteak meat, American cheese, caramelized onions, jalapeños, spicy ketchup and a zippy house sauce, it might sound like a lot. It's not. (For those who don't have access to the exclusive club, that is, most of us, Two Mixed Up's still-in-burger-form "Just a Burger" is available at Town Ball Tavern.)

S’more Cookie from Two Mixed Up seen during a tour of the new food for 2024 at Target Field.

S'more Cookies from Two Mixed Up at Truly on Deck

The second of this Graze Food Hall stand's new ballpark entries is a killer chocolate chip cookie wrapped around a whole gooey s'more. We ate ours at room temperature and loved every sweet bite; we hear that heated up, which they will be at Truly on Deck, makes them transcendent. Club level, right field

Also new this year

Sweet Potato Fritters from StepChld: Sweet and savory shredded sweet potato fritters fried to a crispy ball the size of your fist are part dessert, part brunch at the ballfield. Truly on Deck

Chicken Tinga Arepas from Q'BO Latin Food: Crispy corn pockets are stuffed with pulled chicken, shredded cheese, sour cream, pico de gallo and lots of pickled red onions. Truly on Deck

All-you-can-eat ballpark food: A $42 game ticket comes with as much as you want of hot dogs, burgers, chicken tenders, chips, peanuts, Pepsi products, water and frozen desserts. Legends Landing (Sections S, T, U and V)

Mac N' Meat from East Coast BBQ: Choose one of three toppings for elbows and cheese: chicken, rib tips or pulled pork. Section 131

Deep Fried Oreos from Curds & Cakes: The breaded and deep-fried fair treat makes a stadium appearance. Get a tray of them in a paper boat, or treat them as a topping for a sundae (that's our recommendation). Section 232

Ultimate Burger from Red Cow: Red Cow expands its Target Field menu with this meaty menu mainstay featuring thick patties, aged cheddar, lettuce, tomato, onion and house sauce. Section 233

Mini Donuts from Papa Pete's: There's nothing new about cinnamon-sugar-dusted mini donuts, one of our favorite summer treats. Except for the dipping sauces. Get them with caramel, chocolate or hot honey. Section 136

Spicy Watermelon Margarita and Ultimate Bloody Mary: Not available to most, these two new cocktails join the bar at the new Thrivent Club (formerly Delta). The watermelon marg, with a slight spicy kick, was a favorite. Thrivent Club

Joy Summers is a St. Paul-based food reporter who has been covering Twin Cities restaurants since 2010. She joined the Star Tribune in 2021. 

Sharyn Jackson is a features reporter covering the Twin Cities' vibrant food and drink scene.

  • Minnesota Voters Alliance says new law improperly restored voting rights to felons
  • Gruesome video shown at trial on fatal Apple River stabbing
  • Here's the story LSU coach Kim Mulkey threatened with legal action
  • Uber, Lyft drivers using Hertz program told to return cars, leaving gap before May 1 pullout

After welcoming guests for 67 years, the Tropicana Las Vegas casino's final day has arrived

Japan's royal family makes formal debut on instagram as world's oldest monarchy tries to draw youth.

FILE - Powerball lottery tickets are displayed Oct. 4, 2023, in Surfside, Fla. (AP Photo/Wilfredo Lee, File)

Powerball jackpot rises to $1.09 billion after 3-month-long losing streak continues

On french riviera hillsides, the once-dominant menton lemon gets squeezed by development, music review: vampire weekend's frenetic, challenging 'only god was above us' is an ode to new york.

Electrician Bill Barnes makes repairs in a concourse at Target Field. “Year after year, we try to get more energy efficient,” said Dave Horsman, T

  • The first new foods to find for the Twins 2024 season • Eat & Drink
  • Review: Bûcheron is a landmark restaurant disguised as your friendly neighborhood bistro • Eat & Drink
  • Restaurant openings and closings in the Twin Cities • Eat & Drink
  • Slice Brothers Pizza opens Watch Bar in downtown St. Paul, and more restaurant news • Eat & Drink
  • 4 great new burgers to try in the Twin Cities this spring • Eat & Drink

c union assignment

© 2024 StarTribune. All rights reserved.

IMAGES

  1. C Union

    c union assignment

  2. UNION IN C WITH EXAMPLE- 98

    c union assignment

  3. What is Union in C Programming?

    c union assignment

  4. Unions in C (Solved Problem 1)

    c union assignment

  5. C Union

    c union assignment

  6. Union in C Programing with Example

    c union assignment

VIDEO

  1. Assignment Operator in C Programming

COMMENTS

  1. Union declaration

    Trivial move constructor, move assignment operator, (since C++11) copy constructor and copy assignment operator of union types copy object representations. If the source and the destination are not the same object, these special member functions start lifetime of every object (except for objects that are neither subobjects of the destination nor of implicit-lifetime type) nested in the ...

  2. C Unions

    C Unions. The Union is a user-defined data type in C language that can contain elements of the different data types just like structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to this, only one member can store data at the given instance.

  3. c

    2. In union at a time you can assign one value. In union the values are overlapped with each other. So you are doing the wrong with assigning values to two elements of union. It will always show the last assigned value. So if you are accessing the value of a it will show the last updated value.

  4. Unions (GNU C Language Manual)

    Warning: if the code stores data using one union alternative and accesses it with another, the results depend on the kind of computer in use. Only wizards should try to do this. However, when you need to do this, a union is a clean way to do it. Assignment works on any union type by copying the entire value.

  5. The GNU C Reference Manual

    This is a reference manual for the C programming language as implemented by the GNU Compiler Collection (GCC). Specifically, this manual aims to document: The 1989 ANSI C standard, commonly known as "C89". The 1999 ISO C standard, commonly known as "C99", to the extent that C99 is implemented by GCC. The current state of GNU extensions ...

  6. C Union

    By definition, a union is a type that stores different values in the same memory location but not at the same time. A union is a group of data objects that share a single block of memory. C union syntax. The syntax of defining a union is similar to the syntax of defining a structure type. The following illustrates the syntax for defining a union:

  7. Union in C

    What is a Union in C. In the C programming language, a union is a user-defined data type that allows different types of data to be stored in the same memory location. It provides a way to define a variable that may have different data types, but at any given time, only one member of the union can hold a value.

  8. C

    C - Unions. The union keyword in C lets you define a derived data type, very mush similar to the struct keyword. A union data type in C also that allows to store different data types in the consecutive memory location. However, unlike a struct variable, a variable of union type, only one of its members can contain a value at any given time ...

  9. Union in C Programming

    A union is a data type that can store multiple data values of different types in the same memory location. This is useful when you need to store multiple related values, such as the x, y, and z coordinates of a point. To declare a union in C, you use the following syntax: union my_union {. int x; float y; char z;

  10. Unions in C Programming: Definition & Example

    This is because the final memory assignment was done to record.str, ... Union is a data type in C programming that allows different data types to be stored in the same memory locations. The ...

  11. Union Basics in C

    In line 27, the sizeof() operator is used to print the size of the union. Since we know that, in the case of a union, the compiler allocates sufficient memory to hold the largest member. The largest member of union data is var2 so the sizeof() operator returns 8 bytes which is then printed using the printf() statement.

  12. C++ Unions

    C++ Unions. In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable.

  13. 21 Things to Know Before You Go to Moscow

    1: Off-kilter genius at Delicatessen: Brain pâté with kefir butter and young radishes served mezze-style, and the caviar and tartare pizza. Head for Food City. You might think that calling Food City (Фуд Сити), an agriculture depot on the outskirts of Moscow, a "city" would be some kind of hyperbole. It is not.

  14. C++ union assignment, is there a good way to do this?

    6. In a union, the elements all occupy the same memory, like they sit on top of each other. If you write to another element of a union, it overwrites the others. As such, copying element by element is a waste of time. You could copy the largest element only, but then you would have to know which one that is (not every element of the union has ...

  15. What we know about the Moscow concert hall attack

    CNN —. Russia has been left reeling in the wake of the nation's worst terrorist attack in decades. ISIS has claimed responsibility for the massacre, which saw armed assailants storm a popular ...

  16. [4K] Walking Streets Moscow. Moscow-City

    Walking tour around Moscow-City.Thanks for watching!MY GEAR THAT I USEMinimalist Handheld SetupiPhone 11 128GB https://amzn.to/3zfqbboMic for Street https://...

  17. The A.C.L.U. Said a Worker Used Racist Tropes and Fired Her. But Did

    Then the tables turned, and Ms. Oh was the one slapped with an accusation of serious misconduct. The A.C.L.U. said her complaints about several superiors — all of whom were Black — used ...

  18. The Assignment: "Preachy Females" of the Democratic Party

    A collection of all CNN's political podcasts, featuring episodes from: The Assignment with Audie Cornish, CNN Inside Politics, CNN Political Briefing, The Axe Files, State of the Union, CNN One ...

  19. Baseball players' union head Tony Clark nearly doubled pay to $4.25

    Read More. By RONALD BLUM. Updated 3:23 PM PDT, April 1, 2024. NEW YORK (AP) — Baseball players' association head Tony Clark nearly doubled his salary to $4.25 million in 2023, according the union's annual federal disclosure filing Monday. Clark's salary had risen from just under $2 million when he succeeded Michael Weiner as executive ...

  20. Baseball players' union head Tony Clark nearly doubled pay to $4.25

    Marino earned $215,993 in 2023 before leaving the union last July. After helping minor league players unionize, Marino joined the MLBPA staff in September 2022 and earned $68,977 during the ...

  21. Starbucks violated labor law by barring pro-union buttons, DC Circuit

    Buttons showing support for a Starbucks Union are seen at the Workers United, an affiliate of the Service Employees International Union, offices in Buffalo, New York, U.S., February 23, 2022.

  22. Moscow City 17 quarantine edition 2020 (Half Life 2 universe)

    mashup version of https://youtu.be/mzO_dPMn6H8and https://youtu.be/WdGGnz6oiCwandhttps://youtu.be/1Nc8a9gnDsoby BLR VFX

  23. c

    1 Answer. The start of each element is aligned with the address of the union itself. so the individual comparisons in the expression you ask about are true, but the expression as a whole is false unless the union is located at address 0x0001. The revised version compares distinct pointer types - the pointers should be cast to void pointers.

  24. Brewers designate C Eric Haase for assignment, recall IF Oliver Dunn as

    The Brewers designated Haase for assignment Thursday as they made their final roster moves before Friday's opener at the New York Mets. In other moves, the Brewers recalled infielder Oliver Dunn from Triple-A Nashville, optioned reliever JB Bukauskas to Triple-A Nashville and placed pitchers Taylor Clarke, Wade Miley and Devin Williams on the ...

  25. Brewers send C Eric Haase outright to Triple-A Nashville after he

    The 31-year-old Haase was designated for assignment Thursday. Although Haase batted .395 with a .465 on-base percentage, five homers and 14 RBIs in 18 Cactus League games, he was unable to make ...

  26. Administrative Order: In the Matter of Sarah C. Conley

    The NCUA is aware that on or about March 28, 2022, you were convicted in Onondaga County Court on the offense of Grand Larceny in the Second Degree, P.L. §155.40 (1). State of New York v. Sarah C. Conley, Docket Number: SCI-70992-22/001. Your conviction was in connection with illegal activities at Summit Federal Credit Union, Rochester, New ...

  27. endianness

    A C implementation could choose to always assign only the bytes of the member assigned and to leave the others unchanged. A C implementation may do different things in different circumstances. For example, if there is an isolated assignment, the compiler might just write the byte (s) of the assigned member to memory.

  28. Microsoft splits Teams from Office after antitrust scrutiny

    Updated 12:29 PM PDT, April 1, 2024. REDMOND, Wash. (AP) — Microsoft will stop packaging its Teams videoconferencing app with its Office software after the practice attracted antitrust scrutiny. The tech giant said Monday that customers buying Office subscriptions starting this week won't get Teams bundled with the service.

  29. The first new foods to find for the Twins 2024 season

    Smashed Baked Potato seen during a tour of the new food for 2024 at Target Field in Minneapolis on Monday. Spring is here for real this time as we gear up for that first crack of the bat to echo ...