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

左心房为你撑大大i 提交于 2019-12-13 21:25:58

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/23227486/difference-between-declaration-statement-and-assignment-statement-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!