Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ compiler warning(?) when passing uninitialized local variable to function
    primarykey
    data
    text
    <p>I'm very new to C++ so I'm hoping someone would shed some light. I came across several similar topics but I just need clarification.</p> <p>So it seems it's valid to pass a local string that has been declared but not initialized to a function. But why does compiler complain when you try it with int or float??</p> <p>Whether it's string, float, or int, memory address gets referenced when it is declared even tho it may be "garbage"</p> <pre><code>#include &lt;iostream&gt; using namespace std; void load(int); int main() { int salary; load(salary); return 0; } void load(int sal) { cout &lt;&lt; "your salary: " &lt;&lt; endl; cin &gt;&gt; sal; cout &lt;&lt; sal &lt;&lt; endl; } </code></pre> <p>If I declare int or float as global variable, it works as expected without any warnings. So then is it a better practice to declare variable in global space (I hope not)?</p> <p>So putting it in global, it works :</p> <pre><code>#include &lt;iostream&gt; using namespace std; int salary; void load(int); int main() { load(salary); return 0; } void load(int sal) { cout &lt;&lt; "your salary: " &lt;&lt; endl; cin &gt;&gt; sal; cout &lt;&lt; sal &lt;&lt; endl; } </code></pre> <p>ok, another example to show that uninitialized global variable works when passing to function as value : (going off of David's comment)</p> <pre><code>int foo; int returnit(int j) { cout &lt;&lt; "your salary"; cin &gt;&gt; j; return j; } int main() { int k = returnit(foo); cout &lt;&lt; k; return 0; } </code></pre> <p>anyways, lesson here is to initialize primitive data types before passing to functions.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload