Chapter:Variables and types in C

From Juneday education
Jump to: navigation, search

Meta information about this chapter

Expand using link to the right to see the full content.

Introduction

Variables is a basic building block when developing software in programming languages such as Java and C. In these languages it is important to have a good understanding of what a variable is and how it relates to memory - both as a way to understand how a computer program works and when learning about pointer or references later on.

We need to give the computer a bit of help on how to interpret the variable. We do this by using the type concept, which tells how big the variable is (how much space in memory is used) and how to use the memory for a variable.

It is not enough having variables and types. We, of course, need use them to store values and later on retrieve values. In this lecture we go through how to initialize and assign variables values.

Being able to manage conversion between type, automatic and explicit, are important for a developer. This lecture gives an overview and introduction to type cast.

We've been introduced to types. These have been general so in this chapter we will focus on C and the types found in C.


Purpose

To give the student a basic understanding of variables, types and type cast. This understanding will be used as a basis for future learning.

Types are used in many languages, to different degrees. Being familiar with the type concept is important regardless of language and this presentation gives the student a foundation for future studies.

Declaring variables is done all over the source code of imperative programs (since the only way to create a variable is to declare it).

Without assignment there would not be much a program written in languages such as C, C++ and Java could do. The concept is relatively easy to understand and use but important enough for a separate lecture.

Types are useful in C and a good start in understanding types, variables and expressions.

Goal

The goal of this presentation is to motivate and make the student familiar with the variable concept as well as discuss the way we humans use variables in every day life.

The student shall be able:

  • motivate why variables are needed
  • use variables
  • use and reflect over the type concept
  • convert/cast between different types
  • understand the meaning of an assignment
  • know that the = sign does NOT refer to mathematical equality
  • understand how to use assignments with typed variables
  • use assignment when writing programs
  • be familiar with the type cast concept
  • know the implications of switching between types
  • be able to convert between types
  • know that you can represent whole numbers in C
  • know that you can represent real numbers in C
  • be familiar with int and double and know that there exist other types

Instructions to the teacher

Common problems

Variables are very important to understand. Without this understanding we have found it hard for the students to:

  • to understand functions and their parameter/argument list
  • pointers and reference variables

Chapter videos

All videos in this chapter:

  • Variables and types (eng) (swe) (The video and presentation is based on Java but will do here)

See below for individual links to the videos.

Variables

Description

A memory (storage location) with a name. If we want to store the current temperature in a program, we can store the value in a place in memory and name (using a programming language) that piece of memory for instance current_temperature. Having descriptive names of memory locations greatly helps when writing programs. When we want to use the value of the current temperature again in our program, it is easy to remember and understand what current_temperature stands for.

If you're programming in C you will name the variable current_temperature.

Exercises

  1. We have a variable nr_of_girls (nr_of_girls in C) that has the value 14. We also have a variable called nr_of_boys (nr_of_boys in C)with the value 13. If you were asked to add the values of the two variables together, what would be the result?
  2. Assume a person knows the address of the memory where nr_of_girls is stored. This person writes the value 123 in that memory. What would be the sum of nr_of_girls and nr_of_boys if you were to add them together again?

Solutions

Expand using link to the right to see the full content.

  1. 27. The nr_of_girls has the value 14 and nr_of_boys has the value 13. Adding the values would be adding 13 and 14, which is 27.
  2. 136. The nr_of_girls now has the value 123 and nr_of_boys has the value 13 Adding the values would be adding 123 and 13, which is 136.


Presentation

Presentation: (pdf)

Videos

Variable (eng) (swe) (The presentation and video are based on Java but will do fine here)

Links

Types

Description

A type is a classification to identify different types of data, e.g. integers. Variables in the C programming language have types, which means that we restrict what values are legal to store in variables of certain types. If we want to store and use integer values in our program, we can use a variable of type int (which stands for integer values) for instance. We will then only be able to store integer values in that variable, which helps us to avoid storing something else in the variable by mistake. It can be argued that types helps us making fewer mistakes. This is sometimes called type safety.

Exercises

  1. If you want to count the number of goals in a game of handball, what would be a good type for a variable?
  2. If you want to store the name of a person in a variable, what would be a good type for that name?
  3. You want to store the mean value of the results on an exam. Can you recommend any type?
  4. Add an integer variable with the value 1 with another integer variable with the value 1. What is the resulting sum?

Solutions

Expand using link to the right to see the full content.

  1. Some kind of integer variable. Decimals are not needed - it wouldn't make sense to keep track of a fraction of a goal - e g 1/3 of a goal. The authors do not know of any game that has ended 27.25 - 23. So to keep things simple and to skip the unnecessary, let's use an integer. In C you can use int.
  2. String. String is a reference type, and we'll talk a lot about reference types and classes in later chapters.
  3. It's not unlikely that we'll end up with decimals so a type that supports that would be good. So let's say a double
  4. Adding 1 to 1 is simple. The result is 2.

Presentation

Presentation: (pdf) (This presentation is based on Java but will do here)

Videos

Types (eng) (swe) (This video is based on Java but will do here)

Links

Declaration

Description

Creating a variable in programming languages is done using a declaration. The declaration specifies a name and, in C and many other programming languages, also a type. An example can be int current_temperature; (current_temperature in C)which declares a variable with the name current_temperature and of the type int. In C, int is the name of the type for storing integer values in a certain range.

Exercises

  1. Declare an int variable called nr_student (or nr_student in C).
  2. Imagine we have two variables with exactly the same name. What would be meaning of that? If you find this question hard to answer you're most likely thinking correctly. Don't spend too much time on this question.

Solutions

Expand using link to the right to see the full content.

  1. int nr_student
  2. If it would be possible to declare two variables in the same scope, which is not possible in the languages known by the authors of these lectures and exercises, it would be hard to come up with a reasonable interpretation of what it would mean to use one of the two variables. This is the reason why it is not allowed to use the same variable name twice. At least for now... So the meaning of this would be ... well, hard to come up with.

Presentation

Presentation: (pdf)

Videos

Declaration (eng) (swe)

Links

Wikipedia links for the keen student:


Assignment

Description

With assignments we can modify the value of a variable. An example is current_temperature = 12; (current_temperature = 12; in C) which assigns the value 12 to the variable current_temperature. The assignment is done using the = sign. On the right side of the assignment we can find a literal (e g 12), an expression such as 12*3; or as we will see later on in the course a function/method. When we talk about the = sign, we call it "assignment operator" because its use and meaning is very different from the same sign when used in mathematics, for instance.

Note: a literal is a simple form of expression

Exercises

  1. Declare an integer variable, temperature, and assign it the value 13
  2. Now, the declaration and assignment should be done on the same line.
  3. After the code in (1), assign the value 31 to the temperature variable.
  4. So far we have assigned values to variables. Is that all we can do? No, of course not. But we haven't learned so much about things like functions, expressions and so on. Still we will ask you to assign a calculated value to a variable. Let's first start with agreeing on the fact that 10 + 3 equals 13. If you don't agree we ask you to go to your teacher.. Declare an integer variable, temperature, and assign it the value 12. Declaration and assignment should be done on the same line.
  5. After the code in the previous exercise, assign the temperature variable 10 + 3
  6. Declare an integer variable, count, on one line and assign it the value 12
  7. After the code in the previous exercise, assign the value 31 to the count variable.
  8. Let's use the variable itself on the right side of the assignment operator (=). Assign the variable count the value of itself (the current value) + 10,
    If we as an example say x=x+10 the system starts by checking the right side (x + 10) and calculates (or evaluates) that. If we assume that x had the value 13, then the right side will become 23 since 13 + 10 is 23. After this is done the system will continue by assigning that value, 23, to the x variable.
  9. Let's assume we have two variables as below:
      int nr_girls =  13;
    
      int nr_boys  =  15;
    
      int nr_students;
    
    Assign nr_students the sum of the nr_girls and nr_boys. You should let the computer do the calculation using the +.

Note: The variables are named as in Java Coding Standards, in C you'll use different naming convention for the variables.

Solutions

Expand using link to the right to see the full content.

  1. Let's declare an integer variable. The first thing we need to is to specify the type. In this case we were asked to declare an integer so let's use the integer called int. The next thing we should specify is the name we want to use, let's go for temperature. Ok, finally we should assign the variable a value, to be more specific 13. So let's use the assignment operator. And as always, Java (in particular the Java compiler) wants you to be explicit and specify when your statement is finished. We do this with a ;
      int temperature;
    
      temperature = 13;
    
  2. Let's do the declaration and assignment in one line:
      int temperature = 13;
    
  3. The above is really the same as (1). We're asked to assign a new value. We do this in the same way as in (1), but since the variable temperature is already declared we don't, fact is we can not, again so we're skipping the declaration.
      int temperature =  13;
    
      temperature = 31;
    
  4. This is something we've done before, so let's simply write.
      int temperature =  12;
    
  5. Ok, time to practice on using the + (which is an [operator], more on this later).
      int temperature =  10 + 3;
    
    In the code above, the right hand side (10 + 3) calculated first. After the calculation the assignment is done. The variable now has the value 13.
  6. This should be fairly easy by now:
      int count = 12;
    
  7. Ok , let's assign the variable a new value:
     count = 31;
    
  8. Ok, now we're going to have some fun. If someone asked you to add 3 to the digit written on a post-it note you would have no problem doing that. That's what we're doing on the right side of the assignment operator. And then if someone asked to replace the value on the post it note with the newly calculated sum you'd probably have no problem doing that either, assuming you have a pen. So let's do this in code. Languages such as Java starts of by calculating the sum on the right side, just as we did in the example with the post-it note. And then the sum is assigned to the variable `temperature`.
     count = count + 10 ;
    
  9.   nr_students = nr_girls + nr_boys ;
    
    Again, the right hand side of the assignment operator (=) is calculated before the assignment so the sum of of nr_girls (which has the value 15) and nr_boys (which has the value 13) is calculated to 28 and then the nr_students is assigned that value (28).

Presentation

Presentation: (pdf)

Videos

Assignment (eng) (swe) (The presentation and video are based on Java but will do fine here)

Links

Wikipedia links for the keen student:

Type cast

Description

Some types can store similar values but in different ranges. For integer values, there are more than one type, but the valid values for the different types in the integer family char, short, int, long) vary. A type for storing only a small set of the integers is char. It can only store integer values between -128 and +127. In return, such variables occupy less space of the memory compared to, for instance, int.

If we want to change the type of a variable (or expression) we can do this explicitly in code by using type cast (or typecast). If we want to assign a char variable, last_temperature, with the value of a variable of int type current_temperature and the change the type we can write: last_temperature = (char) current_temperature; When using explicit casts like this, we must be sure that the value will fit inside the target type, or there will be unwanted results. It is always possible to cast from a "smaller type" like char to a "larger type" like int, because the valid values of a smaller interval always fit in the valid range of the larger type.

There are also rules for casting between more complex types than integers etc, but that's for a later chapter!

Exercises

Throughout the following exercises it is assumed that we have the are familiar with following types:

      char -128 through +127
      int  -2 147 483 648 through +2 147 483 647
  1. Will the following code work?
      char nr_students;
    
      nr_students = 123;
    
  2. Will the following code work?
       char nr_students;
    
       nr_students = 789;
    
  3. Will the following code work?
       int nr_students;
    
       nr_students = 123;
    
  4. Will the following code work?
       int nr_students;
    
       nr_students = 789;
    
  5. Will the following code work?
       int male_students = 12;
    
       int female_students = 12;
    
       int nr_students;
    
       char all_students;
    
       nr_students = male_students + female_students;
    
       all_students = nr_students;
    
  6. Make an explicit type cast to tell the compiler you're ok with the conversion.
  7. Will the following code work? This is a question which actually requires a bit of thinking :)
       int male_students = 12;
    
       int female_students = 12;
    
       int nr_students;
    
       nr_students = male_students + female_students;
    
  8. Will the following code work? This is a question which actually requires a bit of thinking :)
       int male_students = 2147483647;
    
       int female_students = 2147483647;
    
       int nr_students;
    
       nr_students = male_students + female_students;
    
  9. Will the following code work? This is a question which actually requires a bit of thinking
       int male_students = 2147483647;
    
       int female_students = 2147483647;
    
       int nr_students;
    
       nr_students = (int)(male_students + female_students);
    
  10. Will the following code work? This is a question which actually requires a bit of thinking
       int male_students   = 123;
    
       int female_students = 123;
    
       char nr_students;
    
       nr_students = (male_students + female_students);
    
  11. Will the following code work? This is a question which actually requires a bit of thinking
       int male_students   = 123;
    
       int female_students = 123;
    
       char nr_students;
    
       nr_students = (char)(male_students + female_students);
    

Solutions

Expand using link to the right to see the full content.

  1. Yes
  2. No. 789 is a bigger value than a char can store. The Java compiler would not allow this. It actually checks the magnitude of literals.
  3. Yes
  4. Yes
  5. Assigning an int value to a char actually works in C (if you're lucky) the compiler accepts it. If it indeed doesn't work the way you wanted, you'll get an overflow or underflow, but the compiler doesn't warn you. An explicit cast doesn't help you much here.
    So assigning the sum of two ints whose sum will fit in a char will actually work (out of luck because the sum did fit in a char), even without a cast.
    You can add a flag to gcc to make it warn about this. Try compiling like this: gcc -Wconversion -Wall. On our computers we get a warning like this:
    typecast.c: In function ‘main’:
    typecast.c:11:19: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
        all_students = nr_students;
                       ^~~~~~~~~~~
    typecast.c:9:9: warning: variable ‘all_students’ set but not used [-Wunused-but-set-variable]
        char all_students;
             ^~~~~~~~~~~~
    
  6. all_students = (char) nr_students
  7. It will work. When the program executes the sum will be calculated to 24, which is possible to store in an int.
  8. It will NOT work. When the program executes the sum will be calculated to a value bigger than the max value of an int. The compiler would allow it but the result would be disastrous (or at least not what we wanted it to be).
  9. It will NOT work. When the program executes the sum will be calculated to a value bigger than the max value of an int. The type cast is ok and the compiler would allow it but the result would be disastrous (or at least not what we wanted it to be).
  10. It will NOT work. The compiler will give an error since you can't store the sum of two ints in a char.
  11. It will work. The compiler is ok with the code, since you do an explicit type cast, and when executing the sum is less the max value of a char.


Presentation

Presentation: (pdf)

Videos

Typecast (eng) (swe) (The presentation and video are based on Java but will do fine here)

Variables and types in C

Description

In this section we will introduce the types most often used in C.

Find the size of some types on your system

If you want to find out the size on the some of them on your computer you can download, compile and execute the program limit.c download link (view source)

To compile:

gcc limit.c -o limit

To execute:

./limit

.. we can't resist showing you a nice trick you can use if you have any of the command line programs curl or wget installed. On GNU/Linux system they're easy to install using the package manager of your distribution. On MacOS curl is already installed. On Windows10 using cygwin you can install using the setup program you downloaded and used when you installed cygwin. To download, compile and execute on one line:

curl https://raw.githubusercontent.com/progund/programming-with-c/master/variables-and-types/limit.c -o limit.c && gcc limit.c -o limit && ./limit

Just copy/paste the line above to a terminal running bash.

Videos

  1. Types in C (eng) (no swedish version) (download presentation) (The presentation and video are based on Java but will do fine here)


Chapter Links

Our C FAQ

External links

Books this chapter is a part of

Programming with C book

Book TOC | previous chapter | next chapter