Bifalgorithm post · Computer science one · Declaration & Assignment

How does assignment and initialization work in C?

How does assignment and initialization work in C? (Computer science one · Declaration & Assignment) — "The assignment operator is a single equal sign, = and is…

Ideas in this flowchart

  • The assignment operator uses = to assign values to variables.
  • Assignment is performed from right to left.
  • The variable receiving the value appears on the left-hand side.
  • The value being assigned appears on the right-hand side.
  • The assigned value may be a literal, variable, or expression.
  • Examples of assigning values to previously declared variables.
  • numUnits = 42;
  • costPerUnit = 32.79;
  • firstInitial = 'C';
  • A declared variable without an assigned value has an undefined initial value.
  • The variable may contain uninitialized memory, garbage, or zero.
  • The C standard does not specify default values for variables.
  • Initial values depend on the compiler, libraries, and operating system.
  • Programs should not assume a variable's initial or default value.
  • If a specific value is required, it must be assigned explicitly.
  • C allows declaration and assignment on the same line.
  • Examples of compact declarations with immediate assignment.
  • int numUnits = 42;
  • double costPerUnit = 32.79;
  • char firstInitial = 'C';
Feed/

How does assignment and initialization work in C?

No cover

Channel

Computer science one

1 page

"The assignment operator is a single equal sign, = and is a right-to-left assignment. The variable that we wish to assign the value to appears on the left-hand-side while the value (literal, variable or expression) is on the right-hand-size. Using our variables from before, we can assign them values:\n\nnumUnits = 42;\n\ncostPerUnit = 32.79;\n\nfirstInitial = 'C';\n\nAn important thing to understand and to keep in mind is: if you declare a variable but do not assign it a value, its value is undefined. If we code something like int a;, the value of the variable a is not necessarily zero; depending on the system, it could contain a special value that indicates “uninitialized memory” or it could contain garbage, or it could have the value zero. The C standard does not specify default values for variables. The default value of variables is highly system dependent–on the compiler, the libraries, and even the operating system. You should not make any assumptions on the initial or default values of variables. If you need such assumptions, then values must be assigned. For brevity, C allows you to declare a variable and immediately assign it a value on the same line. Our example could be written more compactly written as follows:\n\nint numUnits = 42;\n\ndouble costPerUnit = 32.79;\n\nchar firstInitial = 'C';"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.