How to Create Multiple Variables in C Programming - dummies

How to Create Multiple Variables in C Programming

By Dan Gookin

The variable is truly the heart of any programming language, including C, by allowing you to code flexibility into your programs and have it do amazing things.

Exercise 1: Create a program that uses the three integer variables shadrach, meshach, and abednego. Assign integer values to each one, and display the result.

Here’s a copy of the output from the program generated by Exercise 1:

Shadrach is 701
Meshach is 709
Abednego is 719

Your code can generate different text, but the underlying project should work. And give yourself a bonus if your answer matched the answer given here:


#include <stdio.h>
int main()
  int shadrach, meshach, abednego;
  shadrach = 701;
  meshach = 709;
  abednego = 719;
  printf("Shadrach is %dnMeshach is %dnAbednego is %dn",shadrach,meshach,abednego);

When declaring multiple variables of the same type, you can specify all of them on the same line, as shown in The Answer to Exercise 1 (on Line 5). You don’t even have to put spaces after each name; the line could have easily been written

int shadrach,meshach,abednego;

The C compiler doesn’t care about spaces — specifically, white space — outside of something enclosed in double quotes.

You can also stack up the results in a single, long printf() statement. The line wraps in The Answer to Exercise 1 because of page width, and it may wrap on your computer screen as well. But if you type code that wraps, don’t press the Enter key to start a new line.

You can split a long statement in C simply by escaping the Enter key press at the end of a line. Escaping in this context doesn’t mean that you’re fleeing danger (other than offending the compiler); instead, you use the backslash (the escape character) to type the Enter key without messing up your code. To wit:

printf("Shad is %dnMesh is %dnAbed is dn",

You can shorten the names so that the text fits on a line on this page. Between printf()’s formatting string and the variable list, right after the first comma, type a backslash and then pressed the Enter key. The effect is that the line is broken visually, but the compiler still sees it as a single statement. Visually, it looks better.