C Project, Variable, Grocery Store

https://www.codecademy.com/paths/c/tracks/c-basics-sp/modules/variables-c-sp/projects/grocery-store-c-variables

I am quoting one of the key requirements of the project: Grocery Store C Variables.

“9. For display purposes we don’t need the precision that a double offers, instead we will use the variable you created for this purpose. Cast appleReview into the variable appleReviewDisplay (do this after you set the value for appleReview ), feel free to use implicit or explicit casting in this case.”

“…do this after you set the value for appleReview

  • Why? What differences it will make if we do not obey this rule?

“…feel free to use implicit or explicit casting in this case”

  • How to distinguish an implicit from an explicit? And in this scenario, is an implicit casting even possible to begin with?

The instructions want you to use the value appleReview is assigned to, and cast it to an integer and then assign appleReviewDisplay to the new (integer) value. This would not be possible if appleReview weren’t already assigned to the value.

In this case:

appleReviewDisplay = appleReview //implicit
// since appleReviewDisplay was declared as an int, and appleReview
// was declared as a double, the data type is implicitly converted
// from double to int with the above assignment

or

appleReviewDisplay = (int)appleReview //explicit
// here, (int) is an explicit instruction to cast the value to an int
2 Likes

Amazing explanation! Thanks so much for your help :smile:

Another silly question haha…

As you mentioned:
“appleReviewDisplay = appleReview //implicit
// since appleReviewDisplay was declared as an int, and appleReview
// was declared as a double, the data type is implicitly converted
// from double to int with the above assignment”

If, in a completely different scenario, we would want to do the opposite, i.e. casting appleReviewDisplay into appleReview, and that is, casting an int into a double or perhaps float, will it work? Is there any sort of hierarchy by any chance, and if yes, how does it work?

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.