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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Using the math.h Library →← Variable Declaration in CNext lesson: Using the math.h Library →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How do you cast an int to a double in C?
What does a compound assignment operator like += do in C?
Does casting a double to an int round the number in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →