Use of Possibly-Uninitialized Variable

So I am trying to learn rust by creating a simple currency converter like so:

use std::io;

const MYR_TO_USD:f64=0.24;
const USD_TO_MYR:f64=4.16;

fn convert(amount:f64, choice:&str)->f64{
    match choice{
        "dollars"=> return amount*MYR_TO_USD,
        "ringgit"=>return amount*USD_TO_MYR,
        _=>return amount

    }
}


fn main(){

    println!("Please choose a conversion method\n
    1. USD TO MYR\n
    2. MYR TO USD");

    let mut input_text=String::new();

    io::stdin().read_line(&mut input_text).expect("Failed to read input");

    let num= input_text.trim().parse::<u64>().expect("Failed to parse value");

    let choice;
    let sign;
    let converted_sign;

    match num{
        1=>{
            choice="ringgit";
            sign="MYR";
            converted_sign="$"
        }
        2=>{
            choice="dollars";
            sign="$";
            converted_sign="MYR"

        }
        _=>println!("Please pick a number")
    };

    let mut amount_text=String::new();

    println!("Please enter the amount");

    io::stdin().read_line(&mut amount_text).expect("Failed to read amount");

    let amount=amount_text.trim().parse::<f64>().expect("Error. Please enter a valid number");

    println!("The amount is {}{:.2}",converted_sign,convert(amount, choice));
}

But I keep getting the error saying that the variables "converted_sign" and "choice" aren't initialized as you can see here:

  --> src/main.rs:55:38
   |
55 |     println!("The amount is {}{:.2}",converted_sign,convert(amount, choice));
   |                                      ^^^^^^^^^^^^^^ use of possibly-uninitialized `converted_sign`                                                   

error[E0381]: borrow of possibly-uninitialized variable: `choice`
  --> src/main.rs:55:69
   |
55 |     println!("The amount is {}{:.2}",converted_sign,convert(amount, choice));
   |                                                                     ^^^^^^ use of possibly-uninitialized `*choice`  

Can someone explain what I am doing wrong here?

EDIT: Sorry I'm blind. Didn't realize I forgot the return statement in the default case. Thought the issue was with the way I decl

... keep reading on reddit ➑

πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/PrinceN71
πŸ“…︎ Dec 26 2021
🚨︎ report
C# {Get; Set;} seems like creating an uninitialized variable/property with extra steps

I guess I can understand if you want something to be read only or set only, otherwise I'm confused to what its purpose is. The examples I see are always things that would be easier to do if you left it out.

Like this example

class Person 
{ 
public string Name  // property 
{ get; set;} 
}

 class Program 
{ 

static void Main(string[] args) 
{ 
Person myObj = new Person();     
myObj.Name = "Liam";     
Console.WriteLine(myObj.Name); 
} 
}

You get the same effect if you just enter

public string name; in the Person class.

My question is. Is there a difference between Get/Set vs not initializing? When would it be used?

Then on a slightly unrelated note, is there a website that explains this stuff better than the random google searches provide?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Destrucity11
πŸ“…︎ Dec 28 2021
🚨︎ report
Why can't compilers detect simple uninitialized variables?

Here's my code:

#include <stdio.h>

int main(void)
{
	int a;
	for (int i = 0; i < 1; i++) {
		a = a + 1;
	}
	printf("%d\n", a);
	return 0;
}

I run CC=clang CFLAGS="-Wall -Wextra" make example and it compiles merrily without so much as a warning. Running ./example I get a different value every time. Compiling with -O2 doesn't affect warnings. Trying -Weverything, I discover it will only trigger a warning with -Wconditional-uninitialized despite the fact that there is nothing really conditional about it.

I then try GCC, also no warning, and I get 2 every time so it goes even further in pretending everything is fine. Compiling with -O2 triggers the warning.

It turns out, writing a += 1 instead is what will make the compilers realize that the variable is indeed uninitialized.

πŸ‘︎ 17
πŸ’¬︎
πŸ‘€︎ u/redditthinks
πŸ“…︎ Dec 10 2021
🚨︎ report
Uninitialized Stack Variables netmeister.org/blog/stack…
πŸ‘︎ 27
πŸ’¬︎
πŸ‘€︎ u/speckz
πŸ“…︎ Nov 30 2021
🚨︎ report
Uninitialized Stack Variables netmeister.org/blog/stack…
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/speckz
πŸ“…︎ Nov 30 2021
🚨︎ report
How Programmers and Mathematics react to Uninitialized Variables
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/TheInsaneApp
πŸ“…︎ Oct 21 2021
🚨︎ report
Why is it possible to declare an uninitialized reference to a variable in the header file (and is it used/considered good practice?)

Hi everyone,

I have an unusual question because I only saw people at work doing this and it confused me since I could not find anything about it on the internet.

So I have a basic understanding of c++ and as far as I know, c++ does not allow me to create a reference without initializing it. Meaning I can create an uninitialized variable if I want to but if I want a reference then I must give it a value to reference to, which makes sense.

int i; // ok

int& i; // error

int i = 0 // ok

int& j = i // ok

int i = 0 // ok

int& j = i // ok

Now I saw people at work doing exactly that and it confused me because the project builds and works successfully! Here is an example. Let's say we have a class A that has an Api member like the following

// header file

class A {
A() = default;
A(Api &api);

private:
Api& api // does it make a difference if I declared the api attribute not as a reference?
// (like this: Api api and let the rest as it is
}

// cpp file

A::A(Api &api): api{api}

This is what confused me. The api private member/attribute is declared as a reference but it is not initialized so what does it reference exactly? As far as I know, references cannot be Null and must have a value so how can this declaration be possible?

My guess is that it is legit because the declaration is in the header file and the api member will be directly initialized in the constructor so eventually it will refer to something when the program runs and hence the compiler accept this. Am I right?

Can someone explain this to me and even better maybe tell me if this writing has any benefits or if they are using it. I tried to search on the internet about this but I didn't find any c++ code that uses this style of declaring references in the header file.

πŸ‘︎ 27
πŸ’¬︎
πŸ‘€︎ u/nidhaloff
πŸ“…︎ Jun 01 2021
🚨︎ report
using uninitialized variable error

I am running Nginx 1.18 on Ubuntu 20.04.

I am getting the following error in my log every few seconds:

2021/08/25 19:47:11 [warn] 43673#43673: *1320 using uninitialized "path_info" variable, client: 210.54.XX.XX``, server: nextcloud.``mydomain``.co.nz``, request: "PROPFIND /remote.php/dav/files/mike/ HTTP/1.1", host: "nextcloud.mydomain.co.nz"

2021/08/25 19:47:11 [warn] 43673#43673: *1205 using uninitialized "path_info" variable, client: 210.54.XX.XX, server: nextcloud.mydomain.co.nz, request: "GET /ocs/v2.php/apps/notifications/api/v2/notifications HTTP/1.1", host: "nextcloud.mydomain.co.nz", referrer: "https://nextcloud.mydomain.co.nz/settings/user"

2021/08/25 19:47:11 [warn] 43673#43673: *1351 using uninitialized "path_info" variable, client: 210.54.XX.XX, server: nextcloud.mydomain.co.nz, request: "GET /ocs/v2.php/apps/notifications/api/v2/notifications HTTP/1.1", host: "nextcloud.mydomain.co.nz", referrer: "https://nextcloud.mydomain.co.nz/apps/files/?dir=/Business%20computer&fileid=508899"

2021/08/25 19:47:22 [warn] 43673#43673: *1361 using uninitialized "path_info" variable, client: 210.54.XX.XX, server: nextcloud.mydomain.co.nz, request: "GET /ocs/v1.php/cloud/user?format=json HTTP/1.1", host: "nextcloud.mydomain.co.nz"

This is what in /etc/nginx/snippets/fastcgi-php.conf:

# regex to split $uri to $fastcgi_script_name and $fastcgi_path

fastcgi_split_path_info ^(.+?\.php)(/.*)$;

# Check that the PHP script exists before passing it

try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info

# see: http://trac.nginx.org/nginx/ticket/321

set $path_info $fastcgi_path_info;

fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;

include fastcgi.conf;

This is the relevant text in my server block:

`location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|oc[ms]-provider/.+|.+/richd

... keep reading on reddit ➑

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/mike_from_nz
πŸ“…︎ Aug 25 2021
🚨︎ report
[RFC][patch for gcc12][version 1] add -ftrivial-auto-var-init and variable attribute "uninitialized" to gcc gcc.gnu.org/pipermail/gcc…
πŸ‘︎ 53
πŸ’¬︎
πŸ‘€︎ u/mttd
πŸ“…︎ Feb 24 2021
🚨︎ report
Detecting Uninitialized Variables in C++ with the Clang Static Analyzer cyber.bibl.u-szeged.hu/in…
πŸ‘︎ 29
πŸ’¬︎
πŸ‘€︎ u/mttd
πŸ“…︎ Nov 27 2020
🚨︎ report
Why Visual Studio gives me warning for uninitialized variable?

When I declare a variable the Visual Studio gives me a variable is uninitialized warning. I know what it means but I don't understand why should I initialize a variable when I declare it.

Its a good practice to set all variables to something as a default value?

Should I use:

int x;

or

int x = 0;
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/kokosxD
πŸ“…︎ Feb 09 2020
🚨︎ report
Warning that variable is uninitialized even though it is initialized

So there are three similiar warnings that say:

Variable 'ODBCInterface::oi_blocks' is uninitialized. Always initialize a member variable (type.6).
Variable 'ODBCInterface::oi_hstmt_array' is uninitialized. Always initialize a member variable (type.6).
Variable 'ODBCInterface::oi_fExists' is uninitialized. Always initialize a member variable (type.6).

In the function ODBCInterface I have initiliazed the variables:

 for (int i = 0; i < MAX_RESIDENT_CURSORS; i++)
 {
     oi_hstmt_array[i] = SQL_NULL_HSTMT;
     oi_blocks[i] = nullptr;
 }

oi_hstm_array is of type HSTM oi_blocks is a char*

and:

    for (unsigned short& oi_fExist : oi_fExists)
    {
         oi_fExist = 0;
    }

oi_fExist is of type UWORD

So what do I have to do in order to get rid of these warnings?

EDIT:

This is the constructor:

ODBCInterface::ODBCInterface(SqlObjectBase* parent, const char* name):DbInterface(parent, name)
 {
    // try to get decimal char from the locale, so the float values will
    // be compatible with atof() etc.
    oi_long_fetch_mode = LONG_FETCH_MODE_DEFAULT;
    oi_ignore_primary_keys = FALSE;
    oi_ignore_statistics = FALSE;
    oi_with_system_tables = FALSE;

    oi_hdbc = SQL_NULL_HDBC;
    oi_error_nr = 0;
    oi_error_text = NULL;
    oi_subprog_text = NULL;

    oi_supports_owner = TRUE;
    oi_case_sensitive = TRUE;

    oi_cancelled = FALSE;

    oi_blocks[0] = '\0';
    oi_fExists[0] = '\0';
    oi_hstmt_array[0] = '\0';

    for (unsigned short& oi_fExist : oi_fExists)
   {
        oi_fExist = 0;
   }

   for (int i = 0; i < MAX_RESIDENT_CURSORS; i++)
  {
       oi_hstmt_array[i] = SQL_NULL_HSTMT;
       oi_blocks[i] = nullptr;
	
  }

oi_processed_counter = 0;            

oi_buffer = new char[MAX_SQL_NAME_LENGTH];

oi_def_long_size = DEF_LONG_SIZE;
oi_max_long_size = MAX_LONG_SIZE;

oi_tab_list_hstmt = NULL;
oi_view_list_hstmt = NULL;
oi_syn_list_hstmt = NULL;
oi_proc_list_hstmt = NULL;
oi_func_list_hstmt = NULL;

oi_fbuf = new OI_DDFetchBuffer;

oi_username = NULL;
oi_dbms_name = NULL;
oi_opening_quote = NULL;
oi_closing_quote = NULL;
oi_connected = FALSE;
}

This is the header:

private:
    static HENV oi_henv;
    static int oi_ref_count;

    HDBC oi_hdbc;
    SDWORD oi_error_nr;
... keep reading on reddit ➑

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/zongul67
πŸ“…︎ May 05 2020
🚨︎ report
Following the YouTube guide by freeCodeCamp and I'm getting "uninitialized memory" error and "uninitialized local variable __ used" error.

So, I'm learning how to code in my free time and I got an error. I'm sure I'm just formatting something wrong (I'm very new to this), but I can't really understand what it wants me to fix.

Here's the program:

int main()
{

    int secretNum = 7;
    int guess;
    int guessCount = 0;
    int guessLimit = 3;
    bool outOfGuesses = false;

    while(secretNum != guess && !outOfGuesses) {
        if (guessCount < guessLimit) {
            cout << "Enter guess: ";
            cin >> guess;
            guessCount++;

        }
        else {
            outOfGuesses = true;
        }
       
    }


    if(outOfGuesses) {
        cout << "You lost.";

    }
    else {
        cout << "You win!";
    }
    



    





    



    return 0;
}

Like I said, it's probably me just not knowing how to format things yet, but I'm trying my best to learn. Only 2.5 hours of video material into my C++ journey, so I have a lot of learning to do lol.

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/moneyinthepines
πŸ“…︎ Aug 28 2020
🚨︎ report
GCC does not warn about uninitialized variables UB if you add a single, unrelated if statement. godbolt.org/z/ZArcDG
πŸ‘︎ 53
πŸ’¬︎
πŸ‘€︎ u/Xeverous
πŸ“…︎ Jul 30 2019
🚨︎ report
Unobserved quantum particles are probably just uninitialized variables in the simulation that is our universe

mind.blown();

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/HelloItMeMort
πŸ“…︎ May 22 2019
🚨︎ report
Uninitialized Variable
πŸ‘︎ 209
πŸ’¬︎
πŸ‘€︎ u/straemer
πŸ“…︎ Jul 16 2019
🚨︎ report
Help with determining a correct value for a currently uninitialized variable.
#include <iostream>
using namespace std;

int main(){
    int currentSmallestNum;
    int userNum;
    int i = 0;
    cout << "Enter numbers one at time and I will show you the smallest number entered. Enter 0 to stop the program." << endl;
    
    while(i < 1){
            
        cout << "Enter number here: ";
            
        cin >> userNum;
        
        if(userNum != 0){
            if(userNum > currentSmallestNum){
                currentSmallestNum = currentSmallestNum;
            }
        
            if(userNum < currentSmallestNum){
                currentSmallestNum = userNum;
            }
        }
        
        else {
            cout << "The smallest number from the numbers you entered is " << currentSmallestNum << endl;
            i++;
            }
                
        }
        
        return 0;
    }

My homework is to create a program that reads numbers from the user one at a time and does not store them but once zero is entered is supposed to output the smallest number the user entered. As of right now this code can do this but the only test is that it does not pass is when the user enters zero as the first input then the program outputs the smallest number entered is 53285. I'm assuming this is due to having the variable the program is outputting being uninitialized but I'm confused as to what value currentSmallestNum should hold. If it is equal to any integer and the user only inputs integers higher than that integer than the smallest number will be what I integer I assigned it to. How can I avoid this problem? Thanks in advance.

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/Xeivia
πŸ“…︎ May 08 2020
🚨︎ report
How can I detect if a lexical variable exists (is declared) in a package, even if uninitialized? stackoverflow.com/q/61700…
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/EvanCarroll
πŸ“…︎ May 09 2020
🚨︎ report
Uninitialized Bash variable to bypass WAF, tested on CloudFlare WAF and ModSecurity OWASP CRS secjuice.com/web-applicat…
πŸ‘︎ 202
πŸ’¬︎
πŸ‘€︎ u/theMiddleBlue
πŸ“…︎ Sep 02 2018
🚨︎ report
Attacking Uninitialized Variables with Recursion signal11.io/index.php/201…
πŸ‘︎ 120
πŸ’¬︎
πŸ‘€︎ u/maxxori
πŸ“…︎ Nov 22 2017
🚨︎ report
[C] Uninitialized local variable.

I was given the assignment for my intro to programming class to make a calculator for the 4 main functions with if statements. Here's my code. Every time I try and run the code I'm met with the error "Uninitialized local variable". I'm not sure exactly what to do to stop this from happening. I've tried to move the placement of the calculations but no luck. I was just hoping for some advice to get my code running. Thanks in advance.

#include <stdio.h>

int main()

{

float x, y, z, w, j, k;

int a;

printf("Enter 1 for addition. \\n");

printf("Enter 2 for Substraction. \\n");

printf("Enter 3 for multiplication. \\n");

printf("Enter 4 for division. \\n");

scanf\_s(" %d",&amp;a);



z = x + y; /\*calculates sum\*/

w = x - y; /\*calculates difference\*/

j = x / y; /\*calculates quotient\*/

k = x \* y; /\*calculates product\*/



if(a == 1)/\*addition\*/

{

	scanf\_s(" %f", &amp;x); /\* scans for first number\*/

	printf("Enter your second number \\n");

	scanf\_s(" %f", &amp;y); /\*scans for second number\*/

	printf(" %0.2f + %0.2f = %0.2f \\n", x, y, z); /\*prints sum\*/

}

if (a == 2)/\*substraction\*/

{

	scanf\_s(" %f", &amp;x); /\* scans for first number\*/

	printf("Enter your second number \\n");

	scanf\_s(" %f", &amp;y); /\*scans for second number\*/

	printf(" %0.2f - %0.2f= %0.2f \\n", x, y, w); /\*prints difference\*/

}

if (a == 3)/\*multiplication\*/

{

	scanf\_s(" %f", &amp;x); /\* scans for first number\*/

	printf("Enter your second number \\n");

	scanf\_s(" %f", &amp;y); /\*scans for second number\*/

	printf(" %0.2f X %0.2f= %0.2f \\n", x, y, k); /\* prints product\*/

}

if(a == 4)/\*division\*/

{

	scanf\_s(" %f", &amp;x); /\* scans for first number\*/

	printf("Enter your second number \\n");

	scanf\_s(" %f", &amp;y); /\*scans for second number\*/

	printf(" %0.2f / %0.2f= %0.2f \\n",x,y,j); /\* prints quotient\*/

}





return 0;

}

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/CheapTangerine
πŸ“…︎ Sep 27 2018
🚨︎ report
Why C uninitialized global variables have an initial value of zero. utcc.utoronto.ca/~cks/spa…
πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/pdp10
πŸ“…︎ Jan 30 2019
🚨︎ report
variable 'n' is uninitialized
πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/Non_Bot
πŸ“…︎ Jun 11 2018
🚨︎ report
VS 2017 is complaining about uninitialized private variables despite being initialized in another function.

Hello.

The title might be a bit confusing, so allow me to explain.

This is the part of the code which is 'misbehaving'. I have a Reset() method in my class, along with 4 private variables in my class which is in my header file. All the above have only been declared, not defined. My Reset() method is in initialized in the cpp file. It contains the aforementioned private variables except that they're initialized.

Now, this Reset() method is called by the constructor of the class. Everything works except that the compiler complains this . If I initialize the variables inside the constructor itself, the errors go away. Could it be that the compiler doesn't like the constructor getting its values from another method? And is there a fix for that?

Sorry if I haven't provided enough info. Tell me if anything is needed.

Thanks.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Shabbar1
πŸ“…︎ Nov 19 2018
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.