Difference between declaration statement and assignment statement in C? [duplicate]

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.

5,226 5 5 gold badges 32 32 silver badges 50 50 bronze badges asked Apr 22, 2014 at 18:30 143 2 2 gold badges 2 2 silver badges 8 8 bronze badges

2 Answers 2

int a; 
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.)

answered Apr 22, 2014 at 18:31 Russell Zahniser Russell Zahniser 16.3k 40 40 silver badges 31 31 bronze badges The third isn't an assignment. It's initalization. – user395760 Commented Apr 22, 2014 at 18:33

It 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.

– user395760 Commented Apr 22, 2014 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.