I am new to programming and trying to learn C. I am reading a book where I read about these statements but could not understand their meaning.
2 Answers
Declaration:
int a;
Assignment:
a = 3;
Declaration and assignment in one statement:
int a = 3;
Declaration says, "I'm going to use a variable named "a
" to store an integer value." Assignment says, "Put the value 3 into the variable a
."
(As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value. Initialization has special syntax that also supports specifying the contents of a struct or array.)

- 16,188
- 39
- 30
-
6The third isn't an assignment. It's initalization. – Apr 22 '14 at 18:33
-
6It matters in C insofar you can do things in initialization that you can't do in assignment. For example `int a[2] = {};` works but `int a[2]; a = {};` doesn't. – Apr 22 '14 at 18:41
Declaring a variable sets it up to be used at a later point in the code. You can create variables to hold numbers, characters, strings (an array of characters), etc.
You can declare a variable without giving it a value. But, until a variable has a value, it's not very useful.
You declare a variable like so: char myChar;
NOTE: This variable is not initialized.
Once a variable is declared, you can assign a value to it, like: myChar = 'a';
NOTE: Assigning a value to myChar
initializes the variable.
To make things easier, if you know what a variable should be when you declare it, you can simply declare it and assign it a value in one statement: char myChar = 'a';
NOTE: This declares and initializes the variable.
So, once your myChar variable has been given a value, you can then use it in your code elsewhere. Example:
char myChar = 'a';
char myOtherChar = 'b';
printf("myChar: %c\nmyOtherChar: %c", myChar, myOtherChar);
This prints the value of myChar and myOtherChar to stdout (the console), and looks like:
myChar: a
myOtherChar: b
If you had declared char myChar;
without assigning it a value, and then attempted to print myChar
to stdout, you would receive an error telling you that myChar has not been initialized.

- 391
- 1
- 3
- 12
-
You mostly describe the difference between declaring a variable and not initializing it vs. declaring a variable and initializing it. – Apr 22 '14 at 18:42