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 - Booleans
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc 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 - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • C - Functions
  • C - Main Functions
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • 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 - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Nested Structures
  • C - Structure Padding and Packing
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • 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

Assignment Operators in C

In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression.

The value to be assigned forms the right-hand operand, whereas the variable to be assigned should be the operand to the left of the " = " symbol, which is defined as a simple assignment operator in C.

In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Simple Assignment Operator (=)

The = operator is one of the most frequently used operators in C. As per the ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed.

You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable, or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented Assignment Operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression "a += b" has the same effect of performing "a + b" first and then assigning the result back to the variable "a".

Run the code and check its output −

Similarly, the expression "a <<= b" has the same effect of performing "a << b" first and then assigning the result back to the variable "a".

Here is a C program that demonstrates the use of assignment operators in C −

When you compile and execute the above program, it will produce the following result −

To Continue Learning Please Login

Assignment Statement in C

How to assign values to the variables? C provides an  assignment operator  for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C.

The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side.

The syntax of the  assignment expression

Variable = constant / variable/ expression;

The data type of the variable on left hand side should match the data type of constant/variable/expression on right hand side with a few exceptions where automatic type conversions are possible.

Examples of assignment statements,

b = c ; /* b is assigned the value of c */ a = 9 ; /* a is assigned the value 9*/ b = c+5; /* b is assigned the value of expr c+5 */

The expression on the right hand side of the assignment statement can be:

An arithmetic expression; A relational expression; A logical expression; A mixed expression.

The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the right hand side of the variable. Arithmetic operators, relational

Arithmetic operators, relational operators and logical operators are discussed in the following sections.

For example, int a; float b,c ,avg, t; avg = (b+c) / 2; /*arithmetic expression */ a = b && c; /*logical expression*/ a = (b+c) && (b<c); /* mixed expression*/

Share this:

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

Related Posts

  • #define to implement constants
  • Preprocessor in C Language
  • Pointers and Strings

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.

Notify me of follow-up comments by email.

Notify me of new posts by email.

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

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators

Assignment Operators in C

  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

valid c assignment statements

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example:

2. “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Practical C Programming, 3rd Edition by Steve Oualline

Get full access to Practical C Programming, 3rd Edition 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. Basic Declarations and Expressions

A journey of a thousand miles must begin with a single step.

If carpenters made buildings the way programmers make programs, the first woodpecker to come along would destroy all of civilization.

Elements of a Program

If you are going to construct a building, you need two things: the bricks and a blueprint that tells you how to put them together. In computer programming, you need two things: data (variables) and instructions (code or functions). Variables are the basic building blocks of a program. Instructions tell the computer what to do with the variables.

Comments are used to describe the variables and instructions. They are notes by the author documenting the program so that the program is clear and easy to read. Comments are ignored by the computer.

In construction, before we can start, we must order our materials: “We need 500 large bricks, 80 half-size bricks, and 4 flagstones.” Similarly, in C, we must declare our variables before we can use them. We must name each one of our “bricks” and tell C what type of brick to use.

After our variables are defined, we can begin to use them. In construction, the basic structure is a room. By combining many rooms, we form a building. In C, the basic structure is a function. Functions can be combined to form a program.

An apprentice builder does not start out building the Empire State Building, but rather starts on a one-room house. In this chapter, we will concentrate on constructing simple one-function programs.

Basic Program Structure

The basic elements of a program are the data declarations, functions, and comments. Let’s see how these can be organized into a simple C program.

The basic structure of a one-function program is:

Heading comments tell the programmer about the program, and data declarations describe the data that the program is going to use.

Our single function is named main . The name main is special, because it is the first function called. Other functions are called directly or indirectly from main . The function main begins with:

and ends with:

The line return(0); is used to tell the operating system (UNIX or MS-DOS/Windows) that the program exited normally (Status=0). A nonzero status indicates an error—the bigger the return value, the more severe the error. Typically, a status of 1 is used for the most simple errors, like a missing file or bad command-line syntax.

Now, let’s take a look at our Hello World program ( Example 3-1 ).

At the beginning of the program is a comment box enclosed in /* and */ . Following this box is the line:

This statement signals C that we are going to use the standard I/O package. The statement is a type of data declaration. [ 5 ] Later we use the function printf from this package.

Our main routine contains the instruction:

This line is an executable statement instructing C to print the message “Hello World” on the screen. C uses a semicolon ( ; ) to end a statement in much the same way we use a period to end a sentence. Unlike line-oriented languages such as BASIC, an end-of-line does not end a statement. The sentences in this book can span several lines—the end of a line is treated just like space between words. C works the same way. A single statement can span several lines. Similarly, you can put several sentences on the same line, just as you can put several C statements on the same line. However, most of the time your program is more readable if each statement starts on a separate line.

The standard function printf is used to output our message. A library routine is a C procedure or function that has been written and put into a library or collection of useful functions. Such routines perform sorting, input, output, mathematical functions, and file manipulation. See your C reference manual for a complete list of library functions.

Hello World is one of the simplest C programs. It contains no computations; it merely sends a single message to the screen. It is a starting point. After you have mastered this simple program, you have done a number of things correctly.

Simple Expressions

Computers can do more than just print strings—they can also perform calculations. Expressions are used to specify simple computations. The five simple operators in C are listed in Table 4-1 .

Multiply ( * ), divide ( / ), and modulus ( % ) have precedence over add ( + ) and subtract (-). Parentheses, ( ), may be used to group terms. Thus:

yields 12, while:

Example 4-1 computes the value of the expression (1 + 2) * 4 .

Although we calculate the answer, we don’t do anything with it. (This program will generate a “null effect” warning to indicate that there is a correctly written, but useless, statement in the program.)

Think about how confused a workman would be if we were constructing a building and said,

“Take your wheelbarrow and go back and forth between the truck and the building site.” “Do you want me to carry bricks in it?” “No. Just go back and forth.”

We need to store the results of our calculations.

Variables and Storage

C allows us to store values in variables . Each variable is identified by a variable name .

In addition, each variable has a variable type . The type tells C how the variable is going to be used and what kind of numbers (real, integer) it can hold. Names start with a letter or underscore ( _ ), followed by any number of letters, digits, or underscores. Uppercase is different from lowercase, so the names sam , Sam , and SAM specify three different variables. However, to avoid confusion, you should use different names for variables and not depend on case differences.

Nothing prevents you from creating a name beginning with an underscore; however, such names are usually reserved for internal and system names.

Most C programmers use all-lowercase variable names. Some names like int , while , for , and float have a special meaning to C and are considered reserved words . They cannot be used for variable names.

The following is an example of some variable names:

The following are not variable names:

Avoid variable names that are similar. For example, the following illustrates a poor choice of variable names:

A much better set of names is:

Variable Declarations

Before you can use a variable in C, it must be defined in a declaration statement .

A variable declaration serves three purposes:

It defines the name of the variable.

It defines the type of the variable (integer, real, character, etc.).

It gives the programmer a description of the variable. The declaration of a variable answer can be:

The keyword int tells C that this variable contains an integer value. (Integers are defined below.) The variable name is answer . The semicolon ( ; ) marks the end of the statement, and the comment is used to define this variable for the programmer. (The requirement that every C variable declaration be commented is a style rule. C will allow you to omit the comment. Any experienced teacher, manager, or lead engineer will not.)

The general form of a variable declaration is:

where type is one of the C variable types ( int , float , etc.) and name is any valid variable name. This declaration explains what the variable is and what it will be used for. (In Chapter 9 , we will see how local variables can be declared elsewhere.)

Variable declarations appear just before the main() line at the top of a program.

One variable type is integer. Integer numbers have no fractional part or decimal point. Numbers such as 1, 87, and -222 are integers. The number 8.3 is not an integer because it contains a decimal point. The general form of an integer declaration is:

A calculator with an 8-digit display can only handle numbers between 99999999 and -99999999. If you try to add 1 to 99999999, you will get an overflow error. Computers have similar limits. The limits on integers are implementation dependent, meaning they change from computer to computer.

Calculators use decimal digits (0-9). Computers use binary digits (0-1) called bits. Eight bits make a byte. The number of bits used to hold an integer varies from machine to machine. Numbers are converted from binary to decimal for printing.

On most UNIX machines, integers are 32 bits (4 bytes), providing a range of 2147483647 (2 31 -1) to -2147483648. On the PC, most compilers use only 16 bits (2 bytes), so the range is 32767 (2 15 -1) to -32768. These sizes are typical. The standard header file limits.h defines constants for the various numerical limits. (See Chapter 18 , for more information on header files.)

The C standard does not specify the actual size of numbers. Programs that depend on an integer being a specific size (say 32 bits) frequently fail when moved to another machine.

Question 4-1 : The following will work on a UNIX machine, but will fail on a PC :

Why does this fail? What will be the result when it is run on a PC? (Click here for the answer Section 4.12 )

Assignment Statements

Variables are given a value through the use of assignment statements. For example:

is an assignment. The variable answer on the left side of the equal sign ( = ) is assigned the value of the expression (1 + 2) * 4 on the right side. The semicolon ( ; ) ends the statement.

Declarations create space for variables. Figure 4-1 A illustrates a variable declaration for the variable answer . We have not yet assigned it a value so it is known as an uninitialized variable . The question mark indicates that the value of this variable is unknown.

Assignment statements are used to give a variable a value. For example:

is an assignment. The variable answer on the left side of the equals operator ( = ) is assigned the value of the expression (1 + 2) * 4 . So the variable answer gets the value 12 as illustrated in Figure 4-1 B.

The general form of the assignment statement is:

The = is used for assignment. It literally means: Compute the expression and assign the value of that expression to the variable. (In some other languages, such as PASCAL, the = operator is used to test for equality. In C, the operator is used for assignment.)

In Example 4-2 , we use the variable term to store an integer value that is used in two later expressions.

A problem exists with this program. How can we tell if it is working or not? We need some way of printing the answers.

printf Function

The library function printf can be used to print the results. If we add the statement:

the program will print:

The special characters %d are called the integer conversion specification . When printf encounters a %d , it prints the value of the next expression in the list following the format string. This is called the parameter list .

The general form of the printf statement is:

where format is the string describing what to print. Everything inside this string is printed verbatim except for the %d conversions. The value of expression-1 is printed in place of the first %d , expression-2 is printed in place of the second, and so on.

Figure 4-2 shows how the elements of the printf statement work together to generate the final result.

The format string "Twice %d is %d\n" tells printf to display Twice followed by a space, the value of the first expression, then a space followed by is and a space, the value of the second expression, finishing with an end-of-line (indicated by \n ).

Example 4-3 shows a program that computes term and prints it via two printf functions.

The number of %d conversions in the format should exactly match the number of expressions in the printf . C will not verify this. (Actually, the GNU gcc compiler will check printf arguments, if you turn on the proper warnings.) If too many expressions are supplied, the extra ones will be ignored. If there are not enough expressions, C will generate strange numbers for the missing expressions.

Floating Point

Because of the way they are stored internally, real numbers are also known as floating-point numbers. The numbers 5.5, 8.3, and -12.6 are all floating-point numbers. C uses the decimal point to distinguish between floating-point numbers and integers. So 5.0 is a floating-point number, while 5 is an integer. Floating-point numbers must contain a decimal point. Floating-point numbers include: 3.14159, 0.5, 1.0, and 8.88.

Although you could omit digits before the decimal point and specify a number as .5 instead of 0.5, the extra clearly indicates that you are using a floating-point number. A similar rule applies to 12. versus 12.0. A floating-point zero should be written as 0.0.

Additionally, the number may include an exponent specification of the form:

For example, 1.2e34 is a shorthand version of 1.2 x 10 34 .

The form of a floating-point declaration is:

Again, there is a limit on the range of floating-point numbers that the computer can handle. This limit varies widely from computer to computer. Floating-point accuracy will be discussed further in Chapter 16 .

When a floating-point number using printf is written , the %f conversion is used. To print the expression 1.0/3.0 , we use this statement:

Floating Point Versus Integer Divide

The division operator is special. There is a vast difference between an integer divide and a floating-point divide. In an integer divide, the result is truncated (any fractional part is discarded). So the value of 19/10 is 1.

If either the divisor or the dividend is a floating-point number, a floating-point divide is executed. So 19.0/10.0 is 1.9. (19/10.0 and 19.0/10 are also floating-point divides; however, 19.0/10.0 is preferred for clarity.) Several examples appear in Table 4-2 .

C allows the assignment of an integer expression to a floating-point variable. C will automatically perform the conversion from integer to floating point. A similar conversion is performed when a floating-point number is assigned to an integer. For example:

Notice that the expression 1 / 2 is an integer expression resulting in an integer divide and an integer result of 0.

Question 4-2 : Why is the result of Example 4-4 0.0”? What must be done to this program to fix it? (Click here for the answer Section 4.12 )

Question 4-3 : Why does 2 + 2 = 5928? (Your results may vary. See Example 4-5 .) (Click here for the answer Section 4.12 )

Question 4-4 : Why is an incorrect result printed? (See Example 4-6 .) (Click here for the answer Section 4.12 )

The type char represents single characters. The form of a character declaration is:

Characters are enclosed in single quotes ( ' ). 'A' , 'a' , and '!' are character constants. The backslash character (\) is called the escape character . It is used to signal that a special character follows. For example, the characters \ " can be used to put a double quote inside a string. A single quote is represented by \' . \n is the newline character. It causes the output device to go to the beginning of the next line (similar to a return key on a typewriter). The characters \\ are the backslash itself. Finally, characters can be specified by \ nnn , where nnn is the octal code for the character. Table 4-3 summarizes these special characters. Appendix A contains a table of ASCII character codes.

While characters are enclosed in single quotes ( ' ), a different data type, the string, is enclosed in double quotes ( " ). A good way to remember the difference between these two types of quotes is to remember that single characters are enclosed in single quotes. Strings can have any number of characters (including one), and they are enclosed in double quotes.

Characters use the printf conversion %c . Example 4-7 reverses three characters.

When executed, this program prints:

Answer 4-1 : The largest number that can be stored in an int on most UNIX machines is 2147483647. When using Turbo C++, the limit is 32767. The zip code 92126 is larger than 32767, so it is mangled, and the result is 26590.

This problem can be fixed by using a long int instead of just an int . The various types of integers will be discussed in Chapter 5 .

Answer 4-2 : The problem concerns the division: 1/3 . The number 1 and the number 3 are both integers, so this question is an integer divide. Fractions are truncated in an integer divide. The expression should be written as:

Answer 4-3 : The printf statement:

tells the program to print a decimal number, but there is no variable specified. C does not check to make sure printf is given the right number of parameters. Because no value was specified, C makes one up. The proper printf statement should be:

Answer 4-4 : The problem is that in the printf statement, we used a %d to specify that an integer was to be printed, but the parameter for this conversion was a floating-point number. The printf function has no way of checking its parameters for type. So if you give the function a floating-point number, but the format specifies an integer, the function will treat the number as an integer and print unexpected results.

Programming Exercises

Exercise 4-1 : Write a program to print your name, social security number, and date of birth.

Exercise 4-2 : Write a program to print a block E using asterisks ( * ), where the E has a height of seven characters and a width of five characters.

Exercise 4-3 : Write a program to compute the area and perimeter of a rectangle with a width of three inches and a height of five inches. What changes must be made to the program so that it works for a rectangle with a width of 6.8 inches and a length of 2.3 inches?

Exercise 4-4 : Write a program to print “HELLO” in big block letters; each letter should have a height of seven characters and width of five characters.

Exercise 4-5 : Write a program that deliberately makes the following mistakes:

Prints a floating-point number using the %d conversion.

Prints an integer using the %f conversion.

Prints a character using the %d conversion.

[ 5 ] Technically, the statement causes a set of data declarations to be taken from an include file. Chapter 10 , discusses include files.

Get Practical C Programming, 3rd Edition 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.

valid c assignment statements

Intro to C for CS31 Students

Part 2: structs & pointers.

  • Pointers and Functions C style "pass by referece"
  • Dynamic Memory Allocation (malloc and free)
  • Pointers to Structs

Defining a struct type

Declaring variables of struct types, accessing field values, passing structs to functions, rules for using pointer variables.

  • Next, initialize the pointer variable (make it point to something). Pointer variables store addresses . Initialize a pointer to the address of a storage location of the type to which it points. One way to do this is to use the ampersand operator on regular variable to get its address value: int x; char ch; ptr = &x; // ptr get the address of x, pointer "points to" x ------------ ------ ptr | addr of x|--------->| ?? | x ------------ ------ cptr = &ch; // ptr get the address of ch, pointer "points to" ch cptr = &x; // ERROR! cptr can hold a char address only (it's NOT a pointer to an int) All pointer variable can be set to a special value NULL . NULL is not a valid address but it is useful for testing a pointer variable to see if it points to a valid memory address before we access what it points to: ptr = NULL; ------ ------ cptr = NULL; ptr | NULL |-----| cptr | NULL |----| ------ ------
  • Use *var_name to dereference the pointer to access the value in the location that it points to. Some examples: int *ptr1, *ptr2, x, y; x = 8; ptr1 = NULL; ptr2 = &x; ------------ ------ ptr2 | addr of x|--------->| 8 | x ------------ ------ *ptr2 = 10; // dereference ptr2: "what ptr2 points to gets 10" ------------ ----- ptr2 | addr of x|--------->| 10 | x ------------ ----- y = *ptr2 + 3; // dereference ptr2: "y gets what ptr2 points to plus 3" ----- ----- ptr1 = ptr2; // ptr1 gets address value stored in ptr2 ------------ ----- ptr2 | addr of x |--------->| 10 | x ------------ ----- /\ ------------ | ptr1 | addr of x |-------------- ------------ // TODO: finish tracing through this code and show what is printed *ptr1 = 100; ptr1 = &y; *ptr1 = 80; printf("x = %d y = %d\n", x, y); printf("x = %d y = %d\n", *ptr2, *ptr1);
  • and what does this mean with respect to the value of each argument after the call?
  • Implement a program with a swap function that swaps the values stored in its two arguments. Make some calls to it in main to test it out.

malloc and free

Pointers, the heap, and functions, linked lists in c.

  • Assignment Statement

An Assignment statement is a statement that is used to set a value to the variable name in a program .

Assignment statement allows a variable to hold different types of values during its program lifespan. Another way of understanding an assignment statement is, it stores a value in the memory location which is denoted by a variable name.

Assignment Statement Method

The symbol used in an assignment statement is called as an operator . The symbol is ‘=’ .

Note: The Assignment Operator should never be used for Equality purpose which is double equal sign ‘==’.

The Basic Syntax of Assignment Statement in a programming language is :

variable = expression ;

variable = variable name

expression = it could be either a direct value or a math expression/formula or a function call

Few programming languages such as Java, C, C++ require data type to be specified for the variable, so that it is easy to allocate memory space and store those values during program execution.

data_type variable_name = value ;

In the above-given examples, Variable ‘a’ is assigned a value in the same statement as per its defined data type. A data type is only declared for Variable ‘b’. In the 3 rd line of code, Variable ‘a’ is reassigned the value 25. The 4 th line of code assigns the value for Variable ‘b’.

Assignment Statement Forms

This is one of the most common forms of Assignment Statements. Here the Variable name is defined, initialized, and assigned a value in the same statement. This form is generally used when we want to use the Variable quite a few times and we do not want to change its value very frequently.

Tuple Assignment

Generally, we use this form when we want to define and assign values for more than 1 variable at the same time. This saves time and is an easy method. Note that here every individual variable has a different value assigned to it.

(Code In Python)

Sequence Assignment

(Code in Python)

Multiple-target Assignment or Chain Assignment

In this format, a single value is assigned to two or more variables.

Augmented Assignment

In this format, we use the combination of mathematical expressions and values for the Variable. Other augmented Assignment forms are: &=, -=, **=, etc.

Browse more Topics Under Data Types, Variables and Constants

  • Concept of Data types
  • Built-in Data Types
  • Constants in Programing Language 
  • Access Modifier
  • Variables of Built-in-Datatypes
  • Declaration/Initialization of Variables
  • Type Modifier

Few Rules for Assignment Statement

Few Rules to be followed while writing the Assignment Statements are:

  • Variable names must begin with a letter, underscore, non-number character. Each language has its own conventions.
  • The Data type defined and the variable value must match.
  • A variable name once defined can only be used once in the program. You cannot define it again to store other types of value.
  • If you assign a new value to an existing variable, it will overwrite the previous value and assign the new value.

FAQs on Assignment Statement

Q1. Which of the following shows the syntax of an  assignment statement ?

  • variablename = expression ;
  • expression = variable ;
  • datatype = variablename ;
  • expression = datatype variable ;

Answer – Option A.

Q2. What is an expression ?

  • Same as statement
  • List of statements that make up a program
  • Combination of literals, operators, variables, math formulas used to calculate a value
  • Numbers expressed in digits

Answer – Option C.

Q3. What are the two steps that take place when an  assignment statement  is executed?

  • Evaluate the expression, store the value in the variable
  • Reserve memory, fill it with value
  • Evaluate variable, store the result
  • Store the value in the variable, evaluate the expression.

Customize your course in 30 seconds

Which class are you in.

tutor

Data Types, Variables and Constants

  • Variables in Programming Language
  • Concept of Data Types
  • Declaration of Variables
  • Type Modifiers
  • Access Modifiers
  • Constants in Programming Language

Leave a Reply Cancel reply

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

Download the App

Google Play

cppreference.com

Statements are fragments of the C program that are executed in sequence. The body of any function is a compound statement, which, in turn is a sequence of statements and declarations:

There are five types of statements:

[ edit ] Labels

Any statement can be labeled , by providing a name followed by a colon before the statement itself.

Any statement (but not a declaration) may be preceded by any number of labels , each of which declares identifier to be a label name, which must be unique within the enclosing function (in other words, label names have function scope ).

Label declaration has no effect on its own, does not alter the flow of control, or modify the behavior of the statement that follows in any way.

[ edit ] Compound statements

A compound statement, or block , is a brace-enclosed sequence of statements and declarations.

The compound statement allows a set of declarations and statements to be grouped into one unit that can be used anywhere a single statement is expected (for example, in an if statement or an iteration statement):

Each compound statement introduces its own block scope .

The initializers of the variables with automatic storage duration declared inside a block and the VLA declarators are executed when flow of control passes over these declarations in order, as if they were statements:

[ edit ] Expression statements

An expression followed by a semicolon is a statement.

Most statements in a typical C program are expression statements, such as assignments or function calls.

An expression statement without an expression is called a null statement . It is often used to provide an empty body to a for or while loop. It can also be used to carry a label in the end of a compound statement or before a declaration:

[ edit ] Selection statements

The selection statements choose between one of several statements depending on the value of an expression.

[ edit ] Iteration statements

The iteration statements repeatedly execute a statement.

[ edit ] Jump statements

The jump statements unconditionally transfer flow control.

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.8 Statements and blocks (p: 106-112)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.8 Statements and blocks (p: 146-154)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.8 Statements and blocks (p: 131-139)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.6 STATEMENTS

[ edit ] See also

  • 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 12 February 2022, at 03:36.
  • This page has been accessed 110,310 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

Tutorials Class - Logo

  • C All Exercises & Assignments

Write a C program to check whether a number is even or odd

Description:

Write a C program to check whether a number is even or odd.

Note: Even number is divided by 2 and give the remainder 0 but odd number is not divisible by 2 for eg. 4 is divisible by 2 and 9 is not divisible by 2.

Conditions:

  • Create a variable with name of number.
  • Take value from user for number variable.

Enter the Number=9 Number is Odd.

Write a C program to swap value of two variables using the third variable.

You need to create a C program to swap values of two variables using the third variable.

You can use a temp variable as a blank variable to swap the value of x and y.

  • Take three variables for eg. x, y and temp.
  • Swap the value of x and y variable.

Write a C program to check whether a user is eligible to vote or not.

You need to create a C program to check whether a user is eligible to vote or not.

  • Minimum age required for voting is 18.
  • You can use decision making statement.

Enter your age=28 User is eligible to vote

Write a C program to check whether an alphabet is Vowel or Consonant

You need to create a C program to check whether an alphabet is Vowel or Consonant.

  • Create a character type variable with name of alphabet and take the value from the user.
  • You can use conditional statements.

Enter an alphabet: O O is a vowel.

Write a C program to find the maximum number between three numbers

You need to write a C program to find the maximum number between three numbers.

  • Create three variables in c with name of number1, number2 and number3
  • Find out the maximum number using the nested if-else statement

Enter three numbers: 10 20 30 Number3 is max with value of 30

Write a C program to check whether number is positive, negative or zero

You need to write a C program to check whether number is positive, negative or zero

  • Create variable with name of number and the value will taken by user or console
  • Create this c program code using else if ladder statement

Enter a number : 10 10 is positive

Write a C program to calculate Electricity bill.

You need to write a C program to calculate electricity bill using if-else statements.

  • For first 50 units – Rs. 3.50/unit
  • For next 100 units – Rs. 4.00/unit
  • For next 100 units – Rs. 5.20/unit
  • For units above 250 – Rs. 6.50/unit
  • You can use conditional statements.

Enter the units consumed=278.90 Electricity Bill=1282.84 Rupees

Write a C program to print 1 to 10 numbers using the while loop

You need to create a C program to print 1 to 10 numbers using the while loop

  • Create a variable for the loop iteration
  • Use increment operator in while loop

1 2 3 4 5 6 7 8 9 10

  • C Exercises Categories
  • C Top Exercises
  • C Decision Making

clear sunny desert yellow sand with celestial snow bridge

1.7 Java | Assignment Statements & Expressions

An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement . In Java, the equal sign = is used as the assignment operator . The syntax for assignment statements is as follows:

An expression represents a computation involving values, variables, and operators that, when taking them together, evaluates to a value. For example, consider the following code:

You can use a variable in an expression. A variable can also be used on both sides of the =  operator. For example:

In the above assignment statement, the result of x + 1  is assigned to the variable x . Let’s say that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus the following statement is wrong:

Note that the math equation  x = 2 * x + 1  ≠ the Java expression x = 2 * x + 1

Java Assignment Statement vs Assignment Expression

Which is equivalent to:

And this statement

is equivalent to:

Note: The data type of a variable on the left must be compatible with the data type of a value on the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and does not accept the double value 1.0 without Type Casting .

◄◄◄BACK | NEXT►►►

What's Your Opinion? Cancel reply

Enhance your Brain

Subscribe to Receive Free Bio Hacking, Nootropic, and Health Information

HTML for Simple Website Customization My Personal Web Customization Personal Insights

DISCLAIMER | Sitemap | ◘

SponserImageUCD

HTML for Simple Website Customization My Personal Web Customization Personal Insights SEO Checklist Publishing Checklist My Tools

Top Posts & Pages

1. VbScript | Message Box

IMAGES

  1. 51. Assignment and Multiple Assignment Statement in C Programming (Hindi)

    valid c assignment statements

  2. Solved Which of the following assignment statements are

    valid c assignment statements

  3. WEEK ppt download

    valid c assignment statements

  4. Solved: Constance and Hugo make conclusions based on given t[algebra

    valid c assignment statements

  5. Identify valid variable names as per C programming rules

    valid c assignment statements

  6. SDT for Assignment Statement

    valid c assignment statements

VIDEO

  1. C++

  2. Decision Making & Conditional Statement in C Language Part

  3. Augmented assignment operators in C

  4. Assignment Operator in C Programming

  5. NPTEL Problem Solving Through Programming In C Week 0 Quiz Assignment Solution

  6. C PROGRAMMING

COMMENTS

  1. Assignment Operators in C

    Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −. int g = 20; // valid statement 10 = 20; // invalid statement Augmented Assignment Operators

  2. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  3. Assignment Statement in C Programming Language

    C provides an assignment operator for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C. The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side. The syntax of the assignment expression

  4. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  5. The Assignment Statement

    The meaning of the first assignment is computing the sum of the value in Counter and 1, and saves it back to Counter. Since Counter 's current value is zero, Counter + 1 is 1+0 = 1 and hence 1 is saved into Counter. Therefore, the new value of Counter becomes 1 and its original value 0 disappears. The second assignment statement computes the ...

  6. 4. Basic Declarations and Expressions

    Variables are given a value through the use of assignment statements. For example: answer = (1 + 2) * 4; is an assignment. The variable answer on the left side of the equal sign (=) is assigned the value of the expression (1 + 2) * 4 on the right side. The semicolon (;) ends the statement.Declarations create space for variables.

  7. Valid to use assignment operator in C expression?

    Or, how I would say it: "The assignment operator is an expression." That is, it sets it apart from "an assignment statement" found in other languages like Python. C merely allows (all?) expressions in "statement context". (Python allows x = y = 42 but not x = (y = 42) showing that it's just a special statement construct.) -

  8. CS31: Introduction to C Programming

    An lvalue is an expression that can appear on the left hand side of an assignment statement. In C, single variables or array elements are lvalues. ... The following example illustrates valid and invalid C assignment statements based on lvalue status: struct studentT student1; studentT student2; int x; char arr[10], ch; x = 10; // valid C: x is ...

  9. CS31: Intro to C Structs and Pointers

    An lvalue is an expression that can appear on the left hand side of an assignment statement. In C, single variables or array elements are lvalues. ... The following example illustrates valid and invalid C assignment statements based on lvalue status: struct studentT student1; studentT student2; int x; char arr[10], ch; x = 10; // valid C: x is ...

  10. What are Assignment Statement: Definition, Assignment Statement ...

    Assignment Statement. An Assignment statement is a statement that is used to set a value to the variable name in a program. Assignment statement allows a variable to hold different types of values during its program lifespan. Another way of understanding an assignment statement is, it stores a value in the memory location which is denoted.

  11. Expression Statement (GNU C Language Manual)

    19.1 Expression Statement. The most common kind of statement in C is an expression statement.It consists of an expression followed by a semicolon. The expression's value is discarded, so the expressions that are useful are those that have side effects: assignment expressions, increment and decrement expressions, and function calls.

  12. Statements

    Statements are fragments of the C program that are executed in sequence. The body of any function is a compound statement, which, in turn is a sequence of statements and declarations: int main (void){// start of a compound statementint n =1;// declaration (not a statement) n = n +1;// expression statementprintf("n = %d\n", n );// expression ...

  13. Structure Assignment (GNU C Language Manual)

    15.13 Structure Assignment. Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example: Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

  14. C All Exercises & Assignments

    Write a C program to find the maximum number between three numbers . Description: You need to write a C program to find the maximum number between three numbers. Conditions: Create three variables in c with name of number1, number2 and number3; Find out the maximum number using the nested if-else statement

  15. Which of the following are valid C++ assignment statements ...

    If a = 4; and b = 3;, then after the statement a = b; the value of b is still 3. In the statement cin >> y;, y can only be an int or a double variable. In an output statement, the newline charactermay be a part of the string. The following is a legal C++ program: int main() { return 0; }

  16. C++ ch 2 Flashcards

    Which of the following are not valid assignment statements? A) total = 9; B) 72 = amount; C) yourAge = myAge; B. If the variable letter has been defined as a char variable, which of the following are not valid assignment statements? A) letter = w; B) letter = 'w'; C) letter = "w"; A, C.

  17. 1.7 Java

    An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is as follows: variable ...

  18. In C++ what causes an assignment to evaluate as true or false when used

    An assignment statement evaluates to the new value of the variable assigned to (barring bizarre overloads of operator=). If the assignment happens in a boolean context it will then depend on the type of that value how it is treated. If the value is a bool, it is of course treated as a bool. If the value is a numeric value, a non-zero value is ...

  19. Solved 10. Which of the following are valid C++ assignment

    Your solution's ready to go! Our expert help has broken down your problem into an easy-to-learn solution you can count on. Question: 10. Which of the following are valid C++ assignment statements? Assume that i is an int variable, and x and percent are double variables. a.i - 5 = x; b.i = i++; c.x = x * percent / 100; d.percent = 0.05%; 10 ...

  20. Is this a valid assignment in C++?

    It's valid, number is not being assigned the entire line you see though. i and fanout are 2 other integers also being created at that time, fanout is also being initialized at this time. That one line is equivalent to: int number = config.nodes; int i; int fanout = numP/2; answered Jul 11, 2011 at 19:48. Corey Ogburn.