ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Declaring variables and constants in C

Updated on April 12, 2011

C programs manipulate data through the use of variables and constants. If you haven't already, please click this link: C Data Types, Variables and Constants to get an overview of data types in C.

Variables and constants need to be "declared" before they can be used. A declaration statement in C is a statement that lists an identifier or identifiers and their data type so that they can be used in a program. Recall that an identifier can be a variable, constant or a function. These are the letters or words that you create in your programs.

For example, to declare an integer variable called "busNumber", you'd do this:

int busNumber;

You can also list mutlple identifiers separated by a comma in one line like this:

int busNumber, totalSeats, noOfDrivers, noOfStops;

Note that all the variables above, busNumber, totalSeats, noOfDrivers and noOfStops are all declared as an Integer. You can also do this equally well for the other data types. Please see more examples below for the different ways to declare variables.

float height, weight;
float temperature;
char letterPressed, firstLetter, lastLetter;
char ch;
int min_value, max_value;
int a;
int b;
int c;

Initialization

I've only declared variables so far, however, the declarations above will work exactly the same for constants. Remember, though, that constants can only be assigned a single value and that value can never be changed as the program runs. Furthermore, that value can only be assigned at the time of compilation (also known as "compile-time").

This brings us to the topic of "initialization".

Initialization is the process of assigning the very first value to a variable or constant. For a variable, this can happen on or after declaration. For a constant, however, it can only happen during declaration.

Below are two examples of initializing a variable. Note that the first block of code below initializes the variable after the declaration while the second block of code initializes the variable during declaration.

int startTime;
startTime = 0;
int startTime = 0;

To initialize a constant, you would do it like this:

const int startTime = 0;

If you try to initialize a constant after the declaration, the compiler will give you an error message, something similar to this one:

$ gcc t.c -o t
t.c: In function `main`:
t.c:13: error: assignment of read-only variable `startTime`

Please see more examples below for a mixture of declarations and initializations of variables and constants.

float height = 0.0, weight = 0.0;
float temperature = 37.5;
char letterPressed = '', firstLetter = 'a', lastLetter = 'z';
char ch;
int min_value = -12, max_value = 12;
const int a = 1;
const int b = 5;
int c = 0;

Declare before use

Always remember to declare a variable or constant before you use it, otherwise, if you don't, maybe something like the code block below:

a = 1000;
int a;

The compiler will give you an error complaining about an unknown variable, something similar to this:

$ gcc t.c -o t
t.c: In function `main`:
t.c:13: error: `a` undeclared (first use in this function)
t.c:13: error: (Each undeclared identifier is reported only once
t.c:13: error: for each function it appears in.)

Macro substitution

I'd like to show you a different way of creating constants. Technically this would fall under the topic known as "C preprocessor". However, many programmers would use this facility in order to define constants.

We make use of the preprocessor term "#define". There are many other pre-processor terms that we'll discuss later, but for now, let's simply look at how to use #define to define a constant. Please note that I'm using the term "define" and not "declare", you'll know why shortly.

Here's a statement that would define a constant identifier called "MAX_VALUE".

#define MAX_VALUE 1000000

Three things to note:

  1. "MAX_VALUE" in all capital letters compared to our earlier examples of variables and constants. Actually, you can use the usual small letters as before, however, today's convention would tell you that it's actually good to use capital letters to differenciate them from constants declared with the "const" keyword.
  2. There is no semi-colon character to end the statement.
  3. There is no data type specified.

What this #define does is create a word or letter that gets substituted with the expression defined. In other words, anywhere in your program that "MAX_VALUE" appears, it will be substituted with "1000000". This happens during compilation. Here's an example:

#define MAX_VALUE 1000000

int x, y;

x = MAX_VALUE;

y = MAX_VALUE + 100;

The previous code defines MAX_VALUE to be 1000000 ("one million"). Then we declare two integer variables x and y. Then the x and y assignment statements will be translated by the compiler into this:

x = 1000000;

y = 1000000 + 100;

Note that the compiler simply did a straight substitution of MAX_VALUE with 1000000. Analyze this next one:

#define CINT const int

CINT x = 5;
CINT y = 10;

The code above defines CINT as "const int". Then followed by two lines that started with CINT. These two statements would be translated by the compiler as:

const int x = 5;
const int y = 10;

As before, the compiler simply did a straight substitution and the statements resulted into two valid constant declarations. This behavior of straight substitution is the reason why you don't use a data type when defining constants this way. Imagine what will happen if you do this:

#define const int MAX_VALUE 1000000

The compiler will translate the above code as if you are defining "const" to have the value of "int MAX_VALUE 1000000". In other words, you are not defining "MAX_VALUE" at all.

The same reason for not putting a semi-colon at the end of the #define statement. If you did something like this: (This is a common mistake, by the way, since most C statements end with semi-colon so it's tempting to put one here.)

#define MAX_VALUE 1000000;

int x = MAX_VALUE + 100;

The assignment statement ("x = ") in the previous code will be translated into a code which is not what you wanted, as shown below:

int x = 1000000; + 100;

The #define is pretty powerful, though what often comes with power is responsibility. Therefore use with care.

You can think of more uses of this especially when it comes to functions. However, you'd usually see this #define being used in defining constants.

I hope this has been useful to you in learning C programming. I'll discuss the so-called "operators" next time and combined with your knowledge of variables and constants, you will soon find yourself writing some simple but useful programs.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)