Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Getting Started with C
  • Your First C Program

C Fundamentals

C Variables, Constants and Literals

C Data Types

C Input Output (I/O)

  • C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Check Whether a Character is an Alphabet or not
  • Find ASCII Value of a Character
  • Find the Size of int, float, double and char
  • C isalpha()

C Type Conversion

In C programming, we can convert the value of one data type ( int, float , double , etc.) to another. This process is known as type conversion . Let's see an example,

Here, we are assigning the double value 34.78 to the integer variable number. In this case, the double value is automatically converted to integer value 34 .

This type of conversion is known as implicit type conversion . In C, there are two types of type conversion:

  • Implicit Conversion
  • Explicit Conversion
  • Implicit Type Conversion In C

As mentioned earlier, in implicit type conversion, the value of one type is automatically converted to the value of another type. For example,

The above example has a double variable with a value 4150.12 . Notice that we have assigned the double value to an integer variable.

Here, the C compiler automatically converts the double value 4150.12 to integer value 4150 .

Since the conversion is happening automatically, this type of conversion is called implicit type conversion.

  • Example: Implicit Type Conversion

The code above has created a character variable alphabet with the value 'a' . Notice that we are assigning alphabet to an integer variable.

Here, the C compiler automatically converts the character 'a' to integer 97 . This is because, in C programming, characters are internally stored as integer values known as ASCII Values .

ASCII defines a set of characters for encoding text in computers. In ASCII code, the character 'a' has integer value 97 , that's why the character 'a' is automatically converted to integer 97 .

If you want to learn more about finding ASCII values, visit find ASCII value of characters in C .

  • Explicit Type Conversion In C

In explicit type conversion, we manually convert values of one data type to another type. For example,

We have created an integer variable named number with the value 35 in the above program. Notice the code,

  • (double) - represents the data type to which number is to be converted
  • number - value that is to be converted to double type
  • Example: Explicit Type Conversion

We have created a variable number with the value 97 in the code above. Notice that we are converting this integer to character.

  • (char) - explicitly converts number into character
  • number - value that is to be converted to char type
  • Data Loss In Type Conversion

In our earlier examples, when we converted a double type value to an integer type, the data after decimal was lost.

Here, the data 4150.12 is converted to 4150 . In this conversion, data after the decimal, .12 is lost.

This is because double is a larger data type ( 8 bytes ) than int ( 4 bytes ), and when we convert data from larger type to smaller, there will be data loss..

Similarly, there is a hierarchy of data types in C programming. Based on the hierarchy, if a higher data type is converted to lower type, data is lost, and if lower data type is converted to higher type, no data is lost.

Data is lost when converting from a higher data type to a lower data type

  • data loss - if long double type is converted to double type
  • no data loss - if char is converted to int

Table of Contents

  • Introduction

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

List of all Keywords in C Language

Next: Scope , Previous: Compatible Types , Up: Top   [ Contents ][ Index ]

24 Type Conversions

C converts between data types automatically when that seems clearly necessary. In addition, you can convert explicitly with a cast .

  Casting a value from one type to another.
  Automatic conversion by assignment operation.
  Automatic conversion of function parameters.
  Automatic conversion of arithmetic operands.
  When operand types differ, which one is used?

C Functions

C structures, c reference, c type conversion, type conversion.

Sometimes, you have to convert the value of one data type to another type. This is known as type conversion .

For example, if you try to divide two integers, 5 by 2 , you would expect the result to be 2.5 . But since we are working with integers (and not floating-point values), the following example will just output 2 :

To get the right result, you need to know how type conversion works.

There are two types of conversion in C:

  • Explicit Conversion (manually)

Implicit Conversion

Implicit conversion is done automatically by the compiler when you assign a value of one type to another.

For example, if you assign an int value to a float type:

As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000 .

This can be risky, as you might lose control over specific values in certain situations.

Especially if it was the other way around - the following example automatically converts the float value 9.99 to an int value of 9 :

What happened to .99 ? We might want that data in our program! So be careful. It is important that you know how the compiler work in these situations, to avoid unexpected results.

As another example, if you divide two integers: 5 by 2 , you know that the sum is 2.5 . And as you know from the beginning of this page, if you store the sum as an integer, the result will only display the number 2 . Therefore, it would be better to store the sum as a float or a double , right?

Why is the result 2.00000 and not 2.5 ? Well, it is because 5 and 2 are still integers in the division. In this case, you need to manually convert the integer values to floating-point values. (see below).

Explicit Conversion

Explicit conversion is done manually by placing the type in parentheses () in front of the value.

Considering our problem from the example above, we can now get the right result:

You can also place the type in front of a variable:

And since you learned about "decimal precision" in the previous chapter, you could make the output even cleaner by removing the extra zeros (if you like):

Real-Life Example

Here's a real-life example of data types and type conversion where we create a program to calculate the percentage of a user's score in relation to the maximum score in a game:

C Exercises

Test yourself with exercises.

Use type conversion to make sure that the result of the following example is 1.5 , and not just 1 .

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

cppreference.com

Implicit conversions.

(C11)
Miscellaneous
General
(C11)
(C99)

When an expression is used in the context where a value of a different type is expected, conversion may occur:

Conversions take place in the following situations:

Conversion as if by assignment Default argument promotions Usual arithmetic conversions Value transformations Lvalue conversion Array to pointer conversion Function to pointer conversion Implicit conversion semantics Compatible types Integer promotions Boolean conversion Integer conversions Real floating-integer conversions Real floating-point conversions Complex type conversions Imaginary type conversions Real-complex conversions Real-imaginary conversions Complex-imaginary conversions Pointer conversions Notes References See also

[ edit ] Conversion as if by assignment

  • In the assignment operator, the value of the right-hand operand is converted to the unqualified type of the left-hand operand.
  • In scalar initialization , the value of the initializer expression is converted to the unqualified type of the object being initialized
  • In a function-call expression , to a function that has a prototype, the value of each argument expression is converted to the type of the unqualified declared types of the corresponding parameter
  • In a return statement , the value of the operand of return is converted to an object having the return type of the function

Note that actual assignment, in addition to the conversion, also removes extra range and precision from floating-point types and prohibits overlaps; those characteristics do not apply to conversion as if by assignment.

[ edit ] Default argument promotions

In a function call expression when the call is made to

Each argument of integer type undergoes integer promotion (see below), and each argument of type float is implicitly converted to the type double

Note that float and float are not promoted to double and double in this context.

(since C99)

[ edit ] Usual arithmetic conversions

The arguments of the following arithmetic operators undergo implicit conversions for the purpose of obtaining the common real type , which is the type in which the calculation is performed:

  • binary arithmetic * , / , % , + , -
  • relational operators < , > , <= , >= , == , ! =
  • binary bitwise arithmetic & , ^ , | ,
  • the conditional operator ?:
If one operand has decimal floating type, the other operand shall not have standard floating,

complex, or imaginary type.

(since C23)
  • integer or real floating type to long double
double double (since C99)
  • integer or real floating type to double
(since C99)
  • integer type to float (the only real type possible is float, which remains as-is)
  • If the types are the same, that type is the common type.
  • If the types have the same signedness (both signed or both unsigned), the operand whose type has the lesser conversion rank 1 is implicitly converted 2 to the other type.
  • If the unsigned type has conversion rank greater than or equal to the rank of the signed type, then the operand with the signed type is implicitly converted to the unsigned type.
  • If the signed type can represent all values of the unsigned type, then the operand with the unsigned type is implicitly converted to the signed type.
  • Else, both operands undergo implicit conversion to the unsigned type counterpart of the signed operand's type.

The result type is determined as follows:

z = 1 + 2*I; double f = 3.0; z + f; // z remains as-is, f is converted to double, the result is double complex
(since C99)

As always, the result of a floating-point operator may have greater range and precision than is indicated by its type (see FLT_EVAL_METHOD ).

Note: real and imaginary operands are not implicitly converted to complex because doing so would require extra computation, while producing undesirable results in certain cases involving infinities, NaNs and signed zeros. For example, if reals were converted to complex, 2.0×(3.0+i∞) would evaluate as (2.0+i0.0)×(3.0+i∞) ⇒ (2.0×3.0–0.0×∞) + i(2.0×∞+0.0×3.0) ⇒ NaN+i∞ rather than the correct 6.0+i∞. If imaginaries were converted to complex, i2.0×(∞+i3.0) would evaluate as (0.0+i2.0) × (∞+i3.0) ⇒ (0.0×∞ – 2.0×3.0) + i(0.0×3.0 + 2.0×∞) ⇒ NaN + i∞ instead of –6.0 + i∞.

(since C99)

Note: regardless of usual arithmetic conversions, the calculation may always be performed in a narrower type than specified by these rules under the as-if rule

[ edit ] Value transformations

[ edit ] lvalue conversion.

Any lvalue expression of any non-array type, when used in any context other than

  • as the operand of the address-of operator (if allowed)
  • as the operand of the pre/post increment and decrement operators .
  • as the left-hand operand of the member access (dot) operator.
  • as the left-hand operand of the assignment and compound assignment operators.
  • as the operand of sizeof

undergoes lvalue conversion : the type remains the same, but loses const / volatile / restrict -qualifiers and atomic properties, if any. The value remains the same, but loses its lvalue properties (the address may no longer be taken).

If the lvalue has incomplete type, the behavior is undefined.

If the lvalue designates an object of automatic storage duration whose address was never taken and if that object was uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

This conversion models the memory load of the value of the object from its location.

[ edit ] Array to pointer conversion

Any lvalue expression of array type , when used in any context other than

  • as the operand of the address-of operator
  • as the operand of typeof and typeof_unqual (since C23)
  • as the string literal used for array initialization

undergoes a conversion to the non-lvalue pointer to its first element.

If the array was declared register , the behavior is undefined.

[ edit ] Function to pointer conversion

Any function designator expression, when used in any context other than

undergoes a conversion to the non-lvalue pointer to the function designated by the expression.

[ edit ] Implicit conversion semantics

Implicit conversion, whether as if by assignment or a usual arithmetic conversion , consists of two stages:

[ edit ] Compatible types

Conversion of a value of any type to any compatible type is always a no-op and does not change the representation.

[ edit ] Integer promotions

Integer promotion is the implicit conversion of a value of any integer type with rank less or equal to rank of int or of a bit-field of type _Bool (until C23) bool (since C23) , int , signed int , unsigned int , to the value of type int or unsigned int .

If int can represent the entire range of values of the original type (or the range of values of the original bit-field), the value is converted to type int . Otherwise the value is converted to unsigned int .

The value from a bit-field of a bit-precise integer type is converted to the corresponding bit-precise integer type. Otherwise, bit-precise integer types are exempt from the integer promotion rules.

(since C23)

Integer promotions preserve the value, including the sign:

rank above is a property of every integer type and is defined as follows:

the rank of a bit-precise signed integer type shall be greater than the rank of any standard integer type with less width or any bit-precise integer type with less width. the rank of any bit-precise integer type relative to an extended integer type of the same width is implementation-defined. (since C23)

Note: integer promotions are applied only

  • as part of usual arithmetic conversions (see above)
  • as part of default argument promotions (see above)
  • to the operand of the unary arithmetic operators + and -
  • to the operand of the unary bitwise operator ~
  • to both operands of the shift operators << and >>

A value of any scalar type can be implicitly converted to _Bool(until C23)bool(since C23). The values that compare equal to an integer constant expression of value zero(until C23)are a zero (for arithmetic types), null (for pointer types) or have a type of (since C23) are converted to 0(until C23)false(since C23), all other values are converted to 1(until C23)true(since C23).

0.5; // b1 == 1 (0.5 converted to int would be zero) bool b2 = 2.0* ; // b2 == 1 (but converted to int would be zero) bool b3 = 0.0 + 3.0*I; // b3 == 1 (but converted to int would be zero) bool b4 = 0.0/0.0; // b4 == 1 (NaN does not compare equal to zero) bool b5 = nullptr; // b5 == 0 (since C23: nullptr is converted to false)
(since C99)

[ edit ] Integer conversions

A value of any integer type can be implicitly converted to any other integer type. Except where covered by promotions and boolean conversions above, the rules are:

  • if the target type can represent the value, the value is unchanged
  • otherwise, if the target type is unsigned, the value 2 b , where b is the number of value bits in the target type, is repeatedly subtracted or added to the source value until the result fits in the target type. In other words, unsigned integers implement modulo arithmetic.
  • otherwise, if the target type is signed, the behavior is implementation-defined (which may include raising a signal)

[ edit ] Real floating-integer conversions

A finite value of any real floating type can be implicitly converted to any integer type. Except where covered by boolean conversion above, the rules are:

  • The fractional part is discarded (truncated towards zero).
  • If the resulting value can be represented by the target type, that value is used
  • otherwise, the behavior is undefined

A value of any integer type can be implicitly converted to any real floating type.

  • if the value can be represented exactly by the target type, it is unchanged
  • if the value can be represented, but cannot be represented exactly, the result is an implementation-defined choice of either the nearest higher or nearest lower value, although if IEEE arithmetic is supported, rounding is to nearest. It is unspecified whether FE_INEXACT is raised in this case.
  • if the value cannot be represented, the behavior is undefined, although if IEEE arithmetic is supported, FE_INVALID is raised and the result value is unspecified.

The result of this conversion may have greater range and precision than its target type indicates (see FLT_EVAL_METHOD ).

If control over FE_INEXACT is needed in floating-to-integer conversions, rint and nearbyint may be used.

[ edit ] Real floating-point conversions

A value of any real floating type can be implicitly converted to any other real floating type.

  • If the value can be represented by the target type exactly, it is unchanged
  • if the value can be represented, but cannot be represented exactly, the result is the nearest higher or the nearest lower value (in other words, rounding direction is implementation-defined), although if IEEE arithmetic is supported, rounding is to nearest
This section is incomplete
Reason: check IEEE if appropriately-signed infinity is required

A value of any complex type can be implicitly converted to any other complex type. The real part and the imaginary part individually follow the conversion rules for the real floating types.

d = 0.1 + 0.1*I; float f = d; // f is (0.100000001490116119384765625, 0.100000001490116119384765625)

A value of any imaginary type can be implicitly converted to any other imaginary type. The imaginary part follows the conversion rules for the real floating types.

d = 0.1* ; float f = d; // f is 0.100000001490116119384765625*I

A value of any real floating type can be implicitly converted to any complex type.

A value of any complex type can be implicitly converted to any real floating type

Note: in complex-to-real conversion, a NaN in the imaginary part will not propagate to the real result.

z = 0.5 + 3*I; float f = z; // the imaginary part is discarded, f is set to 0.5 z = f; // sets z to 0.5 + 0*I

A value of any imaginary type can be implicitly converted to any real type (integer or floating-point). The result is always a positive (or unsigned) zero, except when the target type is _Bool(until C23)bool(since C23), in which case boolean conversion rules apply.

A value of any real type can be implicitly converted to any imaginary type. The result is always a positive imaginary zero.

z = 3*I; bool b = z; // Boolean conversion: sets b to true float f = z; // Real-imaginary conversion: sets f to 0.0 z = 3.14; // Imaginary-real conversion: sets z to 0*_Imaginary_I

A value of any imaginary type can be implicitly converted to any complex type.

A value of any complex type can be implicitly converted to any imaginary type

z = I * (3*I); // the complex result -3.0+0i loses real part // sets z to 0*_Imaginary_I
(since C99)

[ edit ] Pointer conversions

A pointer to void can be implicitly converted to and from any pointer to object type with the following semantics:

  • If a pointer to object is converted to a pointer to void and back, its value compares equal to the original pointer.
  • No other guarantees are offered

A pointer to an unqualified type may be implicitly converted to the pointer to qualified version of that type (in other words, const , volatile , and restrict qualifiers can be added). The original pointer and the result compare equal.

Any integer constant expression with value ​ 0 ​ as well as integer pointer expression with value zero cast to the type void * can be implicitly converted to any pointer type (both pointer to object and pointer to function). The result is the null pointer value of its type, guaranteed to compare unequal to any non-null pointer value of that type. This integer or void* expression is known as null pointer constant and the standard library provides one definition of this constant as the macro NULL .

[ edit ] Notes

Although signed integer overflow in any arithmetic operator is undefined behavior, overflowing a signed integer type in an integer conversion is merely unspecified behavior.

On the other hand, although unsigned integer overflow in any arithmetic operator (and in integer conversion) is a well-defined operation and follows the rules of modulo arithmetic, overflowing an unsigned integer in a floating-to-integer conversion is undefined behavior: the values of real floating type that can be converted to unsigned integer are the values from the open interval (-1; Unnn_MAX+1) .

Conversions between pointers and integers (except from pointer to _Bool (until C23) bool (since C23) and (since C99) from integer constant expression with the value zero to pointer), between pointers to objects (except where either to or from is a pointer to void) and conversions between pointers to functions (except when the functions have compatible types) are never implicit and require a cast operator .

There are no conversions (implicit or explicit) between pointers to functions and pointers to objects (including void*) or integers.

[ edit ] References

  • C23 standard (ISO/IEC 9899:2024):
  • 6.3 Conversions (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
  • 6.3 Conversions (p: 37-41)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.3 Conversions (p: 50-56)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.3 Conversions (p: 42-48)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.2 Conversions

[ edit ] See also

for Implicit conversions
  • Todo with reason
  • 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 23 May 2024, at 04:31.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

C Language Basics

C Type Conversion – Implicit & Explicit Type Conversion in C

When variables and constants of different types are combined in an expression then they are converted to same data type. The process of converting one predefined type into another is called type conversion.

Type conversion in c can be classified into the following two types:

Implicit Type Conversion

When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion .

The compiler converts all operands into the data type of the largest operand.

The sequence of rules that are applied while evaluating expressions are given below:

All short and char are automatically converted to int, then,

  • If either of the operand is of type long double, then others will be converted to long double and result will be long double.
  • Else, if either of the operand is double, then others are converted to double.
  • Else, if either of the operand is float, then others are converted to float.
  • Else, if either of the operand is unsigned long int, then others will be converted to unsigned long int.
  • if a long int can represent all values of an unsigned int, the unsigned int is converted to long int.
  • otherwise, both operands are converted to unsigned long int.
  • Else, if either operand is long int then other will be converted to long int.
  • Else, if either operand is unsigned int then others will be converted to unsigned int.

It should be noted that the final result of expression is converted to type of variable on left side of assignment operator before assigning value to it.

Also, conversion of float to int causes truncation of fractional part, conversion of double to float causes rounding of digits and the conversion of long int to int causes dropping of excess higher order bits.

Explicit Type Conversion

The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion.

The explicit type conversion is also known as type casting .

Type casting in c is done in the following form:

(data_type)expression;

where, data_type is any valid c data type, and expression may be constant, variable or expression.

For example,

The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:

  • All integer types to be converted to float.
  • All float types to be converted to double.
  • All character types to be converted to integer.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)

' data-src=

Nice and very helpfull knowledge for a computer student and it is helpfull for me also

' data-src=

Use of simple language n easy to understand … thanks a lot..:)

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.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Type Conversions (C)

  • 6 contributors

Type conversions depend on the specified operator and the type of the operand or operators. Type conversions are performed in the following cases:

When a value of one type is assigned to a variable of a different type or an operator converts the type of its operand or operands before performing an operation

When a value of one type is explicitly cast to a different type

When a value is passed as an argument to a function or when a type is returned from a function

A character, a short integer, or an integer bit field, all either signed or not, or an object of enumeration type, can be used in an expression wherever an integer can be used. If an int can represent all the values of the original type, then the value is converted to int ; otherwise, it is converted to unsigned int . This process is called "integral promotion." Integral promotions preserve value. That is, the value after promotion is guaranteed to be the same as before the promotion. See Usual Arithmetic Conversions for more information.

Expressions and Assignments

Was this page helpful?

Additional resources

Next: Scope , Previous: Compatible Types , Up: GNU C Manual   [ Contents ][ Index ]

24 Type Conversions

C converts between data types automatically when that seems clearly necessary. In addition, you can convert explicitly with a cast .

  • Explicit Type Conversion
  • Assignment Type Conversions
  • Argument Promotions
  • Operand Promotions
  • Common Type

C in a Nutshell by Peter Prinz, Tony Crawford

Get full access to C in a Nutshell and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Chapter 4. Type Conversions

In C, operands of different types can be combined in one operation. For example, the following expressions are permissible:

When the operands have different types, the compiler tries to convert them to a uniform type before performing the operation. In certain cases, furthermore, you must insert type conversion instructions in your program. A type conversion yields the value of an expression in a new type, which can be either the type void (meaning that the value of the expression is discarded: see " Expressions of Type void " in Chapter 2 ), or a scalar type—that is, an arithmetic type or a pointer. For example, a pointer to a structure can be converted into a different pointer type. However, an actual structure value cannot be converted into a different structure type.

The compiler provides implicit type conversions when operands have mismatched types, or when you call a function using an argument whose type does not match the function’s corresponding parameter. Programs also perform implicit type conversion as necessary when initializing variables or otherwise assigning values to them. If the necessary conversion is not possible, the compiler issues an error message.

You can also convert values from one type to another explicitly using the cast operator (see Chapter 5 ):

In the following example, the cast operator causes the division of one integer variable by another to be performed as a floating-point operation:

Because the cast operator has precedence over division, the value of sum in this example is first converted to type double . The compiler must then implicitly convert the divisor, the value of count , to the same type before performing the division.

You should always use the cast operator whenever there is a possibility of losing information, as in a conversion from int to unsigned int , for example. Explicit casts avoid compiler warnings, and also signpost your program’s type conversions for other programmers. For example, using an explicit cast to void when you discard the return value of a function serves as a reminder that you may be disregarding the function’s error indications.

To illustrate the implicit type conversions that the compiler provides, however, the examples in this chapter use the cast operator only when it is strictly necessary.

Conversion of Arithmetic Types

Type conversions are always possible between any two arithmetic types , and the compiler performs them implicitly wherever necessary. The conversion preserves the value of an expression if the new type is capable of representing it. This is not always the case. For example, when you convert a negative value to an unsigned type, or convert a floating-point fraction from type double to the type int , the new type simply cannot represent the original value. In such cases the compiler generally issues a warning.

Hierarchy of Types

When arithmetic operands have different types, the implicit type conversion is governed by the types’ conversion rank . The types are ranked according to the following rules:

Any two unsigned integer types have different conversion ranks. If one is wider than the other, then it has a higher rank.

Each signed integer type has the same rank as the corresponding unsigned type. The type char has the same rank as signed char and unsigned char .

The standard integer types are ranked in the order:

Any standard integer type has a higher rank than an extended integer type of the same width. (Extended integer types are described in the section “Integer Types with Exact Width (C99)” in Chapter 2 .)

Every enumerated type has the same rank as its corresponding integer type (see " Enumerated Types " in Chapter 2 ).

The floating-point types are ranked in the following order:

The lowest-ranked floating-point type, float , has a higher rank than any integer type.

Every complex floating-point type has the same rank as the type of its real and imaginary parts.

Integer Promotion

In any expression, you can always use a value whose type ranks lower than int in place of an operand of type int or unsigned int . You can also use a bit-field as an integer operand (bit-fields are discussed in Chapter 10 ). In these cases, the compiler applies integer promotion : any operand whose type ranks lower than int is automatically converted to the type int , provided int is capable of representing all values of the operand’s original type. If int is not sufficient, the operand is converted to unsigned int .

Integer promotion always preserves the value of the operand. Some examples:

In the last of these statements, the compiler promotes the first addend, the value of var , to the type int or unsigned int before performing the addition. If int and short have the same width, which is likely on a 16-bit computer, then the signed type int is not wide enough to represent all possible values of the unsigned short variable var . In this case, the value of var is promoted to unsigned int . After the addition, the result is converted to unsigned short for assignment to var .

Usual Arithmetic Conversions

The usual arithmetic conversions are the implicit conversions that are automatically applied to operands of different arithmetic types for most operators. The purpose of the usual arithmetic conversions is to find a common real type for all of the operands and the result of the operation.

The usual arithmetic conversions are performed implicitly for the following operators:

Arithmetic operators with two operands: * , / , % , + , and -

Relational and equality operators: < , <= , > , >= , == , and !=

The bitwise operators, & , | , and ^

The conditional operator, ?: (for the second and third operands)

With the exception of the relational and equality operators, the common real type obtained by the usual arithmetic conversions is generally the type of the result. However, if one or more of the operands has a complex floating-point type, then the result also has a complex floating-point type.

The usual arithmetic conversions are applied as follows:

If either operand has a floating-point type, then the operand with the lower conversion rank is converted to a type with the same rank as the other operand. Real types are converted only to real types, however, and complex types only to complex.

In other words, if either operand has a complex floating-point type, the usual arithmetic conversion matches only the real type on which the actual type of the operand is based. Some examples:

If both operands are integers, integer promotion is first performed on both operands. If after integer promotion the operands still have different types, conversion continues as follows:

If one operand has an unsigned type T whose conversion rank is at least as high as that of the other operand’s type, then the other operand is converted to type T .

Otherwise, one operand has a signed type T whose conversion rank is higher than that of the other operand’s type. The other operand is converted to type T only if type T is capable of representing all values of its previous type. If not, then both operands are converted to the unsigned type that corresponds to the signed type T .

The following lines of code contain some examples:

In this example, to evaluate the comparison in the if condition, the value of i , −1, must first be converted to the type unsigned int . The result is a large positive number. On a 32-bit system, that number is 2 32 − 1, and on any system it is greater than limit . Hence, the if condition is false.

In the last line of the example, the value of limit is converted to n ’s type, long , if the value range of long contains the whole value range of unsigned int . If not—for example, if both int and long are 32 bits wide—then both multiplicands are converted to unsigned long .

The usual arithmetic conversions preserve the operand’s value, except in the following cases:

When an integer of great magnitude is converted to a floating-point type, the target type’s precision may not be sufficient to represent the number exactly.

Negative values are outside the value range of unsigned types.

In these two cases, values that exceed the range or precision of the target type are converted as described under " The Results of Arithmetic Type Conversions ,” later in this chapter.

Other Implicit Type Conversions

The compiler also automatically converts arithmetic values in the following cases:

In assignments and initializations, the value of the right operand is always converted to the type of the left operand.

In function calls, the arguments are converted to the types of the corresponding parameters. If the parameters have not been declared, then the default argument promotions are applied: integer promotion is performed on integer arguments, and arguments of type float are promoted to double .

In return statements, the value of the return expression is converted to the function’s return type.

In a compound assignment, such as x += 2.5 , the values of both operands are first subject to the usual arithmetic conversions, then the result of the arithmetic operation is converted, as for a simple assignment, to the type of the left operand. Some examples:

The Results of Arithmetic Type Conversions

Because the different types have different purposes, representational characteristics, and limitations, converting a value from one type to another often involves the application of special rules to deal with such peculiarities. In general, the exact result of a type conversion depends primarily on the characteristics of the target type.

Conversions to _Bool

Any value of any scalar type can be converted to _Bool . The result is 0—i.e., false —if the scalar value is equal to 0; and 1, or true , if it is nonzero. Because a null pointer compares equal to zero, its value becomes false on conversion to _Bool .

Conversions to unsigned integer types other than _Bool

Integer values are always preserved if they are within the range of the new unsigned type—in other words, if they are between 0 and U type _MAX , where U type _MAX is the greatest value that can be represented by unsigned type .

For values outside the new unsigned type’s range, the value after conversion is the value obtained by adding or subtracting ( U type _MAX + 1) as many times as necessary until the result is within the range of the new type. The following example illustrates the assignment of a negative value to an unsigned integer type:

To adjust a signed value of −1 to the variable’s unsigned type, the program implicitly adds USHRT_MAX + 1 to it until a result within the type’s range is obtained. Because −1 + ( USHRT_MAX + 1) = USHRT_MAX , the final statement in the previous example is equivalent to n = USHRT_MAX; .

For positive integer values, subtracting ( U type _MAX + 1) as often as necessary to bring the value into the new type’s range is the same as the remainder of a division by ( U type _MAX + 1), as the following example illustrates:

If unsigned short is 16 bits wide, then its maximum value, USHRT_MAX , is hexadecimal FFFF. When the value FEDCBA is converted to unsigned short , the result is the same as the remainder of a division by hexadecimal 10000 (that’s USHRT_MAX + 1), which is always FFFF or less. In this case, the value assigned to n is hexadecimal DCBA.

To convert a real floating-point number to an unsigned or signed integer type, the compiler discards the fractional part. If the remaining integer portion is outside the range of the new type, the result of the conversion is undefined. Example:

In the initialization of n in this example, the value of x is converted from double to unsigned long by discarding its fractional part, 0.9. The integer part, 2, is the value assigned to n . In the initialization of m , the C99 function round() rounds the value of x to the nearest integer value (whether higher or lower), and returns a value of type double . The fractional part of the resulting double value—3.0 in this case—is thus equal to zero before being discarded through type conversion for the assignment to m .

When a complex number is converted to an unsigned integer type, the imaginary part is first discarded. Then the resulting floating-point value is converted as described previously. Example:

The imaginary part of z is discarded, leaving the real floating-point value −1.7. Then the fractional part of the floating-point number is also discarded. The remaining integer value, −1, is converted to unsigned int by adding UINT_MAX +1, so that the value ultimately assigned to n is equal to UINT_MAX .

Conversions to signed integer types

The problem of exceeding the target type’s value range can also occur when a value is converted from an integer type, whether signed or unsigned, to a different, signed integer type; for example, when a value is converted from the type long or unsigned int to the type int . The result of such an overflow on conversion to a signed integer type, unlike conversions to unsigned integer types, is left up to the implementation.

Most compilers discard the highest bits of the original value’s binary representation and interpret the lowest bits according to the new type. As the following example illustrates, under this conversion strategy the existing bit pattern of an unsigned int is interpreted as a signed int value:

However, depending on the compiler, such a conversion attempt may also result in a signal being raised to inform the program of the value range overflow.

When a real or complex floating-point number is converted to a signed integer type, the same rules apply as for conversion to an unsigned integer type, as described in the previous section.

Conversions to real floating-point types

Not all integer values can be exactly represented in floating-point types. For example, although the value range of the type float includes the range of the types long and long long , float is precise to only six decimal digits. Thus, some long values cannot be stored exactly in a float object. The result of such a conversion is the next lower or next higher representable value, as the following example illustrates:

Remember that the subtraction in this example, like all floating-point arithmetic, is performed with at least double precision (see " Floating-Point Types " in Chapter 2 ). Typical output produced by this code is:

Any value in a floating-point type can be represented exactly in another floating-point type of greater precision. Thus when a double value is converted to long double , or when a float value is converted to double or long double , the value is exactly preserved. In conversions from a more precise to a less precise type, however, the value being converted may be beyond the range of the new type. If the value exceeds the target type’s range, the result of the conversion is undefined. If the value is within the target type’s range, but not exactly representable in the target type’s precision, then the result is the next smaller or next greater representable value. The program in Example 2-2 illustrates the rounding error produced by such a conversion to a less-precise floating-point type.

When a complex number is converted to a real floating-point type, the imaginary part is simply discarded, and the result is the complex number’s real part, which may have to be further converted to the target type as described in this section.

Conversions to complex floating-point types

When an integer or a real floating-point number is converted to a complex type, the real part of the result is obtained by converting the value to the corresponding real floating-point type as described in the previous section. The imaginary part is zero.

When a complex number is converted to a different complex type, the real and imaginary parts are converted separately according to the rules for real floating-point types.

In the first of these two initializations, the integer constant 2 is implicitly converted to double _Complex for assignment to dz . The resulting value of dz is 2.0 + 0.0 × I .

In the initialization of fz , the two parts of the double _Complex value of dz are converted (after the addition) to float , so that the real part of fz is equal to 2.0F , and the imaginary part 1.0F .

Conversion of Nonarithmetic Types

Pointers and the names of arrays and functions are also subject to certain implicit and explicit type conversions. Structures and unions cannot be converted, although pointers to them can be converted to and from other pointer types.

Array and Function Designators

An array or function designator is any expression that has an array or function type. In most cases, the compiler implicitly converts an expression with an array type, such as the name of an array, into a pointer to the array’s first element. The array expression is not converted into a pointer only in the following cases:

When the array is the operand of the sizeof operator

When the array is the operand of the address operator &

When a string literal is used to initialize an array of char or wchar_t

The following examples demonstrate the implicit conversion of array designators into pointers, using the conversion specification %p to print pointer values:

In the initialization of array_length in this example, the expression sizeof(iArray) yields the size of the whole array, not the size of a pointer. However, the same identifier iArray is implicitly converted to a pointer in the other three statements in which it appears:

As an argument in the first printf() call.

As the operand of the dereferencing operator * .

In the pointer arithmetic operations and assignment to iPtr (see also " Modifying and Comparing Pointers " in Chapter 9 ).

The names of character arrays are used as pointers in string operations, as in this example:

In the function call strlen(msg) in this example, the array identifier msg is implicitly converted to a pointer to the array’s first element with the function parameter’s type, const char * . Internally, strlen() merely counts the characters beginning at that address until the first null character, the string terminator.

Similarly, any expression that designates a function, such as a function name, can also be implicitly converted into a pointer to the function. Again, this conversion does not apply when the expression is the operand of the address operator & . The sizeof operator cannot be used with an operand of function type. The following example illustrates the implicit conversion of function names to pointers. The program initializes an array of pointers to functions, then calls the functions in a loop.

Explicit Pointer Conversions

To convert a pointer from one pointer type to another, you must usually use an explicit cast. In some cases the compiler provides an implicit conversion: these cases are described in " Implicit Pointer Conversions ,” later in this chapter. Pointers can also be explicitly converted into integers, and vice versa.

Object pointers

You can explicitly convert an object pointer—that is, a pointer to a complete or incomplete object type—to any other object pointer type. In your program, you must ensure that your use of the converted pointer makes sense. An example:

If the object pointer after conversion does not have the alignment required by the new type, the results of using the pointer are undefined. In all other cases, converting the pointer value back into the original pointer type is guaranteed to yield an equivalent to the original pointer.

If you convert any type of object pointer into a pointer to any char type ( char , signed char , or unsigned char ), the result is a pointer to the first byte of the object. The first byte is considered here to be the byte with the lowest address, regardless of the system’s byte order structure. The following example uses this feature to print a hexadecimal dump of a structure variable:

This example produces output like the following:

The output of the first two bytes, 23 01 , shows that the code was executed on a little-endian system: the byte with the lowest address in the structure myData was the least significant byte of the short member id .

Function pointers

The type of a function always includes its return type, and may also include its parameter types. You can explicitly convert a pointer to a given function into a pointer to a function of a different type. In the following example, the typedef statement defines a name for the type “function that has one double parameter and returns a double value”:

In this example, the function pointer pFunc is assigned the addresses of functions that have different types. However, if the program uses the pointer to call a function whose definition does not match the exact function pointer type, the program’s behavior is undefined.

Implicit Pointer Conversions

The compiler converts certain types of pointers implicitly. Assignments, conditional expressions using the equality operators == and != , and function calls involve implicit pointer conversion in three kinds of cases, which are described individually in the sections that follow. The three kinds of implicit pointer conversion are:

Any object pointer type can be implicitly converted to a pointer to void , and vice versa.

Any pointer to a given type can be implicitly converted into a pointer to a more qualified version of that type—that is, a type with one or more additional type qualifiers.

A null pointer constant can be implicitly converted into any pointer type.

Pointers to void

Pointers to void —that is, pointers of the type void * —are used as “multipurpose” pointers to represent the address of any object, without regard for its type. For example, the malloc() function returns a pointer to void (see Example 2-3 ). Before you can access the memory block, the void pointer must always be converted into a pointer to an object.

Example 4-1 demonstrates more uses of pointers to void . The program sorts an array using the standard function qsort() , which is declared in the header file stdlib.h with the following prototype:

The qsort() function sorts the array in ascending order, beginning at the address array , using the quick-sort algorithm. The array is assumed to have n elements whose size is element_size .

The fourth parameter, compare , is a pointer to a function that qsort() calls to compare any two array elements. The addresses of the two elements to be compared are passed to this function in its pointer parameters. Usually this comparison function must be defined by the programmer. It must return a value that is less than, equal to, or greater than 0 to indicate whether the first element is less than, equal to, or greater than the second.

Example 4-1. A comparison function for qsort()

In Example 4-1 , the malloc() function returns a void * , which is implicitly converted to float * in the assignment to pNumbers . In the call to qsort() , the first argument pNumbers is implicitly converted from float * to void * , and the function name floatcmp is implicitly interpreted as a function pointer. Finally, when the floatcmp() function is called by qsort() , it receives arguments of the type void * , the “universal” pointer type, and must convert them explicitly to float * before dereferencing them to initialize its float variables.

Pointers to qualified object types

The type qualifiers in C are const , volatile , and restrict (see Chapter 11 for details on these qualifiers). For example, the compiler implicitly converts any pointer to int into a pointer to const int where necessary. If you want to remove a qualification rather than adding one, however, you must use an explicit type conversion, as the following example illustrates:

The second to last statement in this example illustrates why pointers to const -qualified types are sometimes called read-only pointers : although you can modify the pointers’ values, you can’t use them to modify objects they point to.

Null pointer constants

A null pointer constant is an integer constant with the value 0, or a constant integer value of 0 cast as a pointer to void . The macro NULL is defined in the header files stdlib.h , stdio.h , and others as a null pointer constant. The following example illustrates the use of the macro NULL as a pointer constant to initialize pointers rather than an integer zero or a null character:

When you convert a null pointer constant to another pointer type, the result is called a null pointer . The bit pattern of a null pointer is not necessarily zero. However, when you compare a null pointer to zero, to NULL , or to another null pointer, the result is always true . Conversely, comparing a null pointer to any valid pointer to an object or function always yields false .

Conversions Between Pointer and Integer Types

You can explicitly convert a pointer to an integer type, and vice versa. The result of such conversions depends on the compiler, and should be consistent with the addressing structure of the system on which the compiled executable runs. Conversions between pointer and integer types can be useful in system programming, and necessary when programs need to access specific physical addresses, such as ROM or memory-mapped I/O registers.

When you convert a pointer to an integer type whose range is not large enough to represent the pointer’s value, the result is undefined. Conversely, converting an integer into a pointer type does not necessarily yield a valid pointer. A few examples:

The last three statements obtain information about the hardware configuration from the system data table, assuming the operating environment allows the program to access that memory area. In a DOS program compiled with the large memory model, pointers are 32 bits wide and consist of a segment address in the higher 16 bits and an offset in the lower 16 bits (often written in the form segment : offset ). Thus the pointer biosPtr in the prior example can be initialized with a long integer constant.

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

type conversion in assignment in c

codingtube

Type Conversion in Assignments: Exploring Data Flexibility in C Programming

C programming is known for its flexibility in handling different data types, allowing developers to perform diverse operations on variables. However, challenges arise when trying to assign values of one data type to another, especially when they are not directly compatible. This is where type conversion in assignments comes into play. In this article, we will delve into the world of type conversions in C, exploring how to handle assignments between different data types while ensuring accurate results. Let’s dive in with practical examples to grasp the concept more effectively.

Understanding Type Conversion in C:

Type conversion, also known as type casting, is the process of converting a variable from one data type to another. This conversion ensures that data can be manipulated and operated upon correctly, even when dealing with diverse data types.

Implicit Type Conversion:

C supports implicit type conversion, where the compiler automatically converts data from one type to another when required. This type conversion happens when the target data type can handle the range and precision of the source data type.

Example: Implicit Type Conversion

Explicit Type Conversion (Type Casting):

Explicit type conversion, or type casting, involves manually converting a variable from one data type to another using casting operators. This method allows developers to control the conversion process and specify the target data type explicitly.

Example: Explicit Type Conversion

Caution with Explicit Type Conversion:

When using explicit type conversion, it’s essential to be cautious about potential precision loss. For example, converting a float to an int will truncate the fractional part, leading to data loss. Ensure that the resulting data type can handle the necessary range and precision for your application.

Example: Precision Loss with Type Casting

Conclusion:

Type conversion in assignments is a crucial aspect of C programming that allows developers to handle diverse data types effectively. Implicit type conversion simplifies assignments when data types are compatible, while explicit type casting offers control over the conversion process. Understanding when and how to perform type conversions ensures accurate results and avoids potential data loss. Armed with this knowledge and practical examples, you can confidently manipulate data, make assignments, and build robust C programs with utmost flexibility. Embrace the power of type conversions to unlock the full potential of C programming. Happy coding!

Leave a Comment Cancel reply

You must be logged in to post a comment.

logo

Type Conversion, Precedence and Associativity of Operators in C

Type conversion in c, type conversion in assignments, precedence (hierarchy) of operators in c, some quick tips.

  • Within nested parentheses, arithmetic operations will be done according to above priority. Expression under innermost parentheses will be solved first.
  • It is advised to use parenthesis in the program carefully. You should type both parentheses first ( ). After that start typing expression inside it. This will remove the errors caused by missed parenthesis.

Associativity of Operators in C

Related posts, basic structure of c program, introduction to c programming language, variables, constants and keywords in c, first c program – print hello world message, leave a comment cancel reply.

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

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Type Conversion in C++

A type cast is basically a conversion from one type to another. There are two types of type conversion:

  • Done by the compiler on its own, without any external trigger from the user.
  • Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.
  • All the data types of the variables are upgraded to the data type of the variable with largest data type. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
  • It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).

Example of Type Implicit Conversion:

           

In C++, it can be done by two ways:

where type indicates the data type to which the final result is converted.

         
  • Static Cast
  • Dynamic Cast
  • Reinterpret Cast
   

Advantages of Type Conversion:

  • This is done to take advantage of certain features of type hierarchies or type representations.
  • It helps to compute expressions containing variables of different data types.

Please Login to comment...

Similar reads.

  • Technical Scripter 2018
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • How to Make Money on Twitch
  • How to activate Twitch on smart TV
  • 105 Funny Things to Do to Make Someone Laugh
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

C Operators and Type Conversion

An operator is a symbol that represents a particular operation that can be performed on some data. The data is called an operand. The operator thus operates on an operand. Operators could be classified as “unary”, “binary” or “ternary” depending on the number of operands i.e, one, two, or three respectively.

  • Unary expression : A unary expressionT contains one operand and a unary operator.
  • Binary expression : A binary expressionT contains two operands separated by one operator.

Unary operators

Unary incerement and binary operators.

The unary increment operator (++) increments the value of the operand by 1. Similarly the unary decrement operator (–) decrements the value by 1.

Postfixing: The unary operators (increment or decrement) when used after the variable, as in p++, acts as a postfix operator. In the expression p++, p is incremented after its value has been used i.e., assigned to x. Prefixing: The unary operators (increment or decrement) when used before the variable, as in ++p, acts as a prefix operator. The expression ++p increments p before its value has been used i.e., assigned to x.

The table below contains some more examples of unary operators.

Unary plus operator +

The T+T (unary plus) operator maintains the value of the operand. The operand can have any arithmetic type or pointer type.

Unary minus operator

The T-T (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. For example, if TqualityT has the value T100T, T-qualityT has the value T-100T.

Logical negation operator !

The expression yields the value 1 (true) if the operand evaluates to 0, and yields the value 0 (false) if the operand evaluates to a nonzero value.

Bitwise negation operator ~

The T~T (bitwise negation) operator yields the bitwise complement of the operand. In the binary representation of the result, every bit has the opposite value of the same bit in the binary representation of the operand. The operand must have an integral type. The result has the same type as the operand but is not an lvalue.

Suppose TxT represents the decimal value T5T. The 16-bit binary representation of TxT is:0000000000000101. The expression T~xT yields the following result (represented here as a 16-bit binary number):1111111111111010.

Address operator &

The T&T (address) operator yields a pointer to its operand. If Tp_to_yT is defined as a pointer to an TintT and TyT as an TintT, the following expression assigns the address of the variable TyT to the pointer Tp_to_yT:

Indirection operator *

The T*T (indirection) operator determines the value referred to by the pointer-type operand. If Tp_to_yT is defined as a pointer to an TintT and TyT as an TintT, the expressions:

cause the variable TyT to receive the value T3T.

The sizeof operator

The sizeof operator returns the number of bytes the operand occupies in memory. The operand may be a variable, a constant or a data type qualifier.

The output of the above program will be compiler-dependent. The sizeof operator is generally used to determine the lengths of entities called arrays and structures when their sizes are not known. It is also used to allocate memory dynamically during program execution.

Binary operators

Arithmetic operators.

The binary arithmetic operators are +, -, *, / and the modulus operator %. Integer division truncates any fractional part. The modulus operator returns the remainder of the integer division. This operator is applicable only for integers and cannot be applied to float or double.

The operators *, / and % all have the same priority, which is higher than the priority of binary addition (+) and subtraction (-). In case of an expression containing the operators having the same precedence, it gets evaluated from left to right. This default precedence can be overridden by using a set of parentheses. If there is more than one set of parentheses, the innermost parentheses will be performed first, followed by the operations within the second innermost pair and so on.

Relational operators

Relational operators are used to compare two operands to check whether they are equal, unequal or one is greater than or less than the other.

The value of the relational expression is of integer type and is 1, if the result of comparison is true and 0 if it is false.

Logical operators

The logical operators && (AND), || (OR) allow two or more expressions to be combined to form a single expression. The expressions involving these operators are evaluated left to right and evaluation stops as soon as the truth or the falsehood of the result is known.

Bitwise operators

The bitwise operators provided by C may only be applied to operands of type char, short, int and long, whether signed or unsigned.

AND & will copy a bit to the result if it exists in both operands.

OR | will copy a bit if it exists in either operand:

XOR ^ copies the bit if it is set in one operand (but not both):

The contents of two variables are swapped without the use of a temporary variable.

Ones Complement

This operator is unary (requires one operand) and has the effect of ‘flipping’ bits.

The left operands value is moved left by the number of bits specified by the right operand.

Please use unsigned variables with these operators to avoid unpredictable results.

Right Shift

The left operands value is moved right by the number of bits specified by the right operand.

Ternary/Conditional Operator

The conditional expressions written with the ternary operator “?:” provides an alternate way to write the if conditional construct. This operator takes three arguments.

The syntax is:

If expression1 is true (i.e. Value is non-zero), then the value returned would be expression2 otherwise the value returned would be expression3.

res contains 1 if num is positive or zero, else it contains 0.

big contains the highest of all the three numbers.

Compound Assignment operators

Most of the binary operators like +, * have a corresponding assignment operator of the form op= where op is one of +, -, *, /, %, &, |, ^. The explanation of these compound assignment operators is given below in the table 2.5.

Consider the value i = 15 for all the expressions given in the table below.

Comma Operator

The comma operator allows grouping two statements where one is expected.

The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.

Consider the expression:

The type and value of the expression are the type and value of e2; the result of evaluating e1 is discarded. The result is an l-value if the right operand is an l-value.

This example illustrates the comma operator:

In this example, each operand of the for statement’s third expression is evaluated independently.The left operand i += i is evaluated first; then the right operand, j––, is evaluated.

Comma operator returns the value of the rightmost operand.

Usage of Comma operator:

Precedence and order of Evaluation

The hierarchy of commonly used operators is shown in the table below.

In case of a tie between operations of the same priority then they are evaluated based on their associativity. You can use parentheses to change the order of the evaluation. If there is more than one set of parentheses, the innermost parentheses will be performed first, followed by the operations within the second innermost pair, and so on.

C, like most languages, does not specify the order in which the operands of an operator are evaluated. Similarly, the order in which function arguments are evaluated is also not specified. So the statement

can produce different results with different compilers, depending on whether n is incremented before power is called. The solution is to write:

When an operator has operands of different types, they are converted to a common type according to a small number of rules. In general, the only automatic conversions are those that convert a “narrower” operand into a “wider” one without losing information, such as converting an integer to a floating-point value.

Implicit arithmetic conversions

If a binary operator like +, -, * or / that takes two operands of different types then the “lower” type is promoted to the “higher” type before the operation proceeds. The result is of the “higher” type.

An arithmetic operation between an integer and integer always yields an integer result. Operation between float and float always yields a float result. Operation between float and integer always yields a float result.

Type conversion in Assignments

In certain cases the type of the expression and the type of the variable on the left-hand side of assignment operator may not be same. In such a case the value of the expression promoted or demoted depending on the type of the variable on the left-hand side of = operator.

In the above example, the first assignment will store 3 to the variable p, because p is an integer variable, it cannot store a float value. The float is demoted to an integer and its value is stored. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b is a float variable.

Type casting

Explicit type conversions can be forced in any expression, with a unary operator called a cast. In the construction:

The expression is converted to the named type by the conversion rules. The precise meaning of a cast is as if the expression were assigned to a variable of the specified type, which is then used in place of the whole construction.

You May Also Like

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Conversions implied by assignment expressions

There are 2 paragraphs in the 6.5.16 chapter of the Standard:

In simple assignment ( = ), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type;

So consider the following code:

Both i and f have arithmetic types so f should be converted to i . The compilation of the code produces an error though:

But when adding explicit cast it compiles fine:

So what kind of conversions are permitted in assignment expressions? I though the conversion in the Standard is equivalent to cast (type) .

Here are my flags:

  • language-lawyer
  • assignment-operator

St.Antario's user avatar

  • 2 Your code should compile. It doesn't because you've configured your compiler to treat this warning as a error. –  HolyBlackCat Commented Sep 13, 2021 at 6:53
  • 2 -Werror means "treat every warning as a error". –  HolyBlackCat Commented Sep 13, 2021 at 7:00
  • 2 -Werror converts warnings to errors. Your compiler is nice enough to generate a warning about the possible value change, you asked it to make it an error while in fact, it's perfectly legal. –  pmg Commented Sep 13, 2021 at 7:00
  • 2 strict conformance to gnu17 ? gnu17 is not Standard compliant... you may want to add -std=c11 (or c99 or c17 ...) gcc.gnu.org/onlinedocs/gcc/… –  pmg Commented Sep 13, 2021 at 7:09
  • 1 You might want to remove -Werror and replace it with -pedantic-errors (and add -std=c?? , as pmg said). Then you still get errors on conformance problems, but all other warnings don't turn into errors. –  HolyBlackCat Commented Sep 13, 2021 at 7:11

From gcc - wiki (since v4.3)

-Wconversion Warn for implicit conversions that may alter a value. This includes conversions between real and integer

0___________'s user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c language-lawyer assignment-operator or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Multi-producer, multi-consumer blocking queue
  • How to NDSolve stiff ODE?
  • Why does counterattacking lead to a more drawish and less dynamic position than defending?
  • Looking for a short story on chess, maybe published in Playboy decades ago?
  • How many engineers/scientists believed that human flight was imminent as of the late 19th/early 20th century?
  • When I use \llap to overlap words, the space between the overlapped words and the rest of the text is too much: how do I fix it?
  • What did Paul mean when he said that God's promises are "Yes"
  • How can Sanhedrin abolish "whole body of Halachah" from the Torah?
  • C++ std::function-like queue
  • Is Entropy time-symmetric?
  • How to reply to a revise and resubmit review, saying is all good?
  • Will "universal" SMPS work at any voltage in the range, even DC?
  • View undo history of Windows Explorer on Win11
  • Trying to find air crash for a case study
  • Drill perpendicular hole through thick lumber using handheld drill
  • Is it possible to draw this picture without lifting the pen? (I actually want to hang string lights this way in a gazebo without doubling up)
  • "There is a bra for every ket, but there is not a ket for every bra"
  • Why is steaming food faster than boiling it?
  • Function with memories of its past life
  • Is Sagittarius A* smaller than we might expect given the mass of the Milky Way?
  • Do I have to use a new background that's been republished under the 2024 rules?
  • Ubuntu 22.04.5 - Final Point Release
  • Stuck as a solo dev
  • Whom did Jesus' followers accompany -- a soldier or a civilian?

type conversion in assignment in c

IMAGES

  1. Type Conversion in C

    type conversion in assignment in c

  2. c programming

    type conversion in assignment in c

  3. Implicit Type Conversion in C with Examples

    type conversion in assignment in c

  4. Type Conversion in C

    type conversion in assignment in c

  5. Type Conversion in C

    type conversion in assignment in c

  6. C Programming Tutorial

    type conversion in assignment in c

VIDEO

  1. Augmented assignment operators in C

  2. Type Conversion in C

  3. Assignment Operator in C Programming

  4. Type Conversion In C++ Language

  5. Safe Type Conversion Using 'as' in C#

  6. Programming C# for Beginners Episode-3: Operators

COMMENTS

  1. C Type Conversion (With Examples)

    printf("Integer Value: %d", number); return 0; } Output. Double Value: 4150.12 Integer Value: 4150. Here, the data 4150.12 is converted to 4150.In this conversion, data after the decimal, .12 is lost. This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert data from larger type to smaller, there will be data loss..

  2. Type Conversion in C

    Type conversion in C is the process of converting one data type to another. The type conversion is only performed to those data types where conversion is possible. Type conversion is performed by a compiler. In type conversion, the destination data type can't be smaller than the source data type. Type conversion is done at compile time and it ...

  3. Assignment Type Conversions (GNU C Language Manual)

    These type conversions occur automatically in certain contexts, which are: An assignment converts the type of the right-hand expression to the type wanted by the left-hand expression. For example, double i; i = 5; converts 5 to double. A function call, when the function specifies the type for that argument, converts the argument value to that type.

  4. Assignment conversions

    In assignment operations, the type of the value being assigned is converted to the type of the variable that receives the assignment. C allows conversions by assignment between integral and floating types, even if information is lost in the conversion. The conversion method used depends on the types involved in the assignment, as described in ...

  5. Type Conversions (GNU C Language Manual)

    24 Type Conversions. C converts between data types automatically when that seems clearly necessary. In addition, you can convert explicitly with a cast. Casting a value from one type to another. Automatic conversion by assignment operation. Automatic conversion of function parameters. Automatic conversion of arithmetic operands.

  6. C Data Type Conversion

    Type Conversion. Sometimes, you have to convert the value of one data type to another type. This is known as type conversion. For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But since we are working with integers (and not floating-point values), the following example will just output 2:

  7. Implicit conversions

    Conversion as if by assignment. In the assignment operator, the value of the right-hand operand is converted to the unqualified type of the left-hand operand.; In scalar initialization, the value of the initializer expression is converted to the unqualified type of the object being initialized ; In a function-call expression, to a function that has a prototype, the value of each argument ...

  8. C Type Conversion

    The explicit type conversion is also known as type casting. Type casting in c is done in the following form: (data_type)expression; where, data_type is any valid c data type, and expression may be constant, variable or expression. For example, x=(int)a+b*d; The following rules have to be followed while converting the expression from one type to ...

  9. Type Conversions (C)

    Type Conversions (C) Type conversions depend on the specified operator and the type of the operand or operators. Type conversions are performed in the following cases: A character, a short integer, or an integer bit field, all either signed or not, or an object of enumeration type, can be used in an expression wherever an integer can be used ...

  10. Type Conversions (GNU C Language Manual)

    24 Type Conversions. C converts between data types automatically when that seems clearly necessary. In addition, you can convert explicitly with a cast. Explicit Type Conversion. Assignment Type Conversions. Argument Promotions. Operand Promotions. Common Type.

  11. 4. Type Conversions

    Buy on Amazon. Chapter 4. Type Conversions. In C, operands of different types can be combined in one operation. For example, the following expressions are permissible: double dVar = 2.5; // Define dVar as a variable of type double. dVar *= 3; // Multiply dVar by an integer constant.

  12. Type Casting in C: Type Conversion, Implicit, Explicit with Example

    If the operands are of two different data types, then an operand having lower data type is automatically converted into a higher data type. This type of type conversion can be seen in the following example. #include<stdio.h>. int main(){. short a=10; //initializing variable of short data type.

  13. Type Conversion in Assignments: Exploring Data Flexibility in C

    Type conversion in assignments is a crucial aspect of C programming that allows developers to handle diverse data types effectively. Implicit type conversion simplifies assignments when data types are compatible, while explicit type casting offers control over the conversion process. Understanding when and how to perform type conversions ...

  14. Type Conversion, Precedence and Associativity of Operators in C

    Type Conversion in C. The process of converting one data type into another data type is known as type conversion. ... Type Conversion in Assignments. It is quite often that the variable on the left hand side of assignment operator (=) does not match the type of variable on its right hand side. In such a case, the value of the whole expression ...

  15. Implicit Type Conversion in C with Examples

    Conversions in Assignment Expressions There are two operands and an assignment operator in an assignment operation. The difference in rank decides the promotion and demotion of the right expression to equalize the rank of left and right expression. ... Type conversion in C is the process of converting one data type to another. The type ...

  16. Implicit conversion during assignment in C?

    For any assignment a = b;, the value of b is converted to a value of the type of a, provided that is possible, and that converted value is assigned to a.So the outermost cast which you propose is redundant. Not all such conversions are possible, though, and a cast can be used to force a conversion, or to create a chain of legitimate conversions where a direct one doesn't exist, as in this next ...

  17. #7: Type Conversion in C

    Step by step video tutorials to learn C Programming for absolute beginners!In this video, we will have a look at implicit and explicit type conversions in C....

  18. Type Conversion in C++

    Explicit Type Conversion: This process is also called type casting and it is user-defined.Here the user can typecast the result to make it of a particular data type. In C++, it can be done by two ways: Converting by assignment: This is done by explicitly defining the required type in front of the expression in parenthesis. This can be also considered as forceful casting.

  19. C Operators and Type Conversion

    Type conversion in Assignments. In certain cases the type of the expression and the type of the variable on the left-hand side of assignment operator may not be same. In such a case the value of the expression promoted or demoted depending on the type of the variable on the left-hand side of = operator. int p, iNum = 30; float b = 3.5; p = b; b ...

  20. c

    In simple assignment ( = ), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand. and. the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type; So consider the following code:

  21. Assignment operator, shorthand assignment and Type conversion in C

    -Assignment operator-Shorthand assignment-Type conversion with examplesC programming playlisthttps://www.youtube.com/watch?v=xKGg8UfR0mM&list=PLYM2_EX_xVvU7N...