Variable Assignment and Typecasting in C | Programming in C

UPI Study › Courses › Programming in C › Free lessons › Lesson 3.3 Free with a free account

Variable Assignment and Typecasting in C

Programming in C · Chapter 3: Data Types, Variables, Math Library, and Console I/OSection 3.3 · lesson 15 of 786 min · free with a free account

← Variable Declaration in CNext lesson: Using the math.h Library →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Assign values, use increment operators and cast types on purpose.

  • Explain how assignment and compound assignment operators work
  • Compare prefix and postfix increment and decrement
  • Place a cast so that a division is done in floating point
  • Predict truncation and narrowing when converting to smaller types

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (813 words). Read along, or search it.

Opening Puzzle

Where Did the Half Go

Priya shares seven prize tickets between two players, and stores the answer in a double. The screen says 3.0. I made it a double, she says. So where did the half go? To find out, we need to know exactly what an assignment does, and how to ask C for a conversion.

Assignment

Right Side First, Then Store

The assignment operator, a single equals sign, doesn't mean equals as in math class. It means: work out the right side, then store the answer in the box on the left. Think of it as an arrow pointing left. That's why tokens equals tokens plus five is legal: read twenty, add five, store twenty-five back. A compound assignment, such as plus equals five, means the same thing, shorter to write and harder to mistype. There's one for each operator: minus, times, divide, and remainder. Run it. Twenty, then 25, then 30, times three is 90, and the remainder after dividing by four is 2. The last line chains assignments. They run right to left: c gets seven, then b, then a, because an assignment produces the value it stored.

Common Slip

Double Equals Stores Nothing

A classic slip: typing double equals when you meant a single one. Double equals only asks whether two values are equal, and throws the answer away. Nothing is stored. Clang notices: equality comparison result unused. And a note suggests the fix: use a single equals, to turn it into an assignment. It's only a warning, so the program still runs, and tokens is still ten. One warning, and nothing stored.

Increment and Decrement

Prefix Versus Postfix

Adding or subtracting one happens so often that C gives it its own operators: plus plus, the increment, and minus minus, the decrement. They come in two flavors. Postfix, after the name, hands over the old value, then adds one. Prefix, before the name, adds one first, then hands over the new value. Run it. Games plus plus gives 5, the old value, and games is now 6. Plus plus games adds first, so it gives 7. On a line of its own, like games minus minus, the two flavors do the same thing. The difference only matters inside a bigger statement.

Undefined Behavior

Changing x Twice in One Statement

One rule: never use plus plus on a variable that appears twice in the same statement. Here, x is changed twice, and C doesn't say which change happens first. That's undefined behavior, so there's no answer worth printing. Clang warns: multiple unsequenced modifications to x. Give each plus plus its own line.

Quick Check

Lives Plus Plus Both Ways

Quick check. Lives starts at three. A gets lives plus plus, then b gets plus plus lives. What are a, b, and lives at the end? Pause and predict. It prints three, five, five. Postfix hands a the old value, three, and lives becomes four. Then prefix adds first: lives becomes five, and b gets that five. Four is never stored in a or b; it only lives in lives for a moment.

Typecasting

Where the Cast Sits Matters

In lesson 3.1, C converted types on its own. A cast is when you ask for a conversion, by writing the new type in parentheses in front of a value. Open paren double, close paren, tokens means: treat this int as a double, right here. It changes the value used in that one spot, not the variable. Where the cast sits decides everything. Run it. Wrong is 3.0: the division was done with ints. Right is 3.5, because the cast touched the seven before dividing. Late is 3.0 too. The cast came after the division, when the half was already gone.

Pitfalls

Truncation and Narrowing

Two more pitfalls in the same run. Truncation: int of 9.99 is nine, and int of minus 2.7 is minus two. Decimals are cut off toward zero. Nothing is rounded. And narrowing. A char is one byte, and 321 doesn't fit. On this machine it wraps around, and 65 comes out. Other setups may differ, so never rely on it.

Quick Check

Eleven Points Over Four Rounds

Quick check. Eleven points over four rounds. This time the cast sits on the right side of the division, and the average is then cast to an int. What does the program print? Pause and predict. It prints 2.75 and 2. A cast on either side, before the division, makes it a double division, so eleven divided by four is 2.75. Then int of 2.75 cuts the decimals off. It doesn't round to three.

Story Ending

A Cast on the Seven

Back to Priya's seven tickets. Sam traced the line: the division happened first, with ints, so her double only received the leftover 3. She added a double cast on the seven, and the screen said 3.5.

Key Takeaways

Assign, Increment and Cast

To recap. Assignment works out the right side, then stores it on the left, and compound operators like plus equals are shortcuts. Postfix plus plus hands over the old value, prefix the new one. Never change a variable twice in one statement. A cast must touch a value before the operation. Casting to int cuts toward zero, and squeezing into a char loses data.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Variable Assignment and Typecasting in C

What is the difference between ++x and x++ in C?
The prefix form ++x adds one first and gives the new value, while the postfix form x++ gives the old value and then adds one. If lives is 3, a = lives++ stores 3 in a and makes lives 4, then b = ++lives makes lives 5 and stores 5 in b. On a line of its own, either form simply adds one.
How do you cast an int to a double in C?
Write the target type in parentheses before the value, as in (double)tokens. The cast changes the value used at that spot, not the variable itself. Its position matters: (double)7 / 2 gives 3.5 because one operand is a double before the division, but (double)(7 / 2) gives 3.0 because the integer division has already dropped the half.
What does a compound assignment operator like += do in C?
A compound assignment operator combines an operation with storing the result, so tokens += 5 means tokens = tokens + 5. C has one for each arithmetic operator, including -=, *=, /= and %=. Starting from 25, tokens += 5 gives 30, then tokens *= 3 gives 90, and tokens %= 4 gives 2. The short form is quicker to write and harder to mistype.
Does casting a double to an int round the number in C?
No, casting a double to an int truncates toward zero instead of rounding. (int)9.99 gives 9, and (int)-2.7 gives -2. To round to the nearest whole number, use a function such as round from math.h. A related risk is narrowing: 321 does not fit in a one-byte char, and on many systems it wraps to 65, a result that should never be relied on.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →