Quick question regarding IF ELSE

Hi, noob here with a quick question.... In the following code I'm trying to initialize int limit with a value using the if else statement. However when I try to compile, the compiler says that the limit variable is uninitialized. Can someone please tell me what I'm doing wrong and how to correct it? Thanks in advance....


#include "stdafx.h"
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
int cyear;

cout << "What is the current year?" << endl;
cin >> cyear;

if(cyear > 1980)
int limit = 10;
else
int limit = 5;

cout << limit << endl;

system("pause");
return 0;
}
In fact the code

1
2
3
4
if(cyear > 1980)
int limit = 10;
else
int limit = 5;


looks like

1
2
3
4
5
6
7
8
if(cyear > 1980)
{
   int limit = 10;
}
else
{
   int limit = 5;
}



that is limit are local variables that are alive until 'if' and 'else' are executed.

To correct your code you should write

1
2
3
4
5
int limit;
if(cyear > 1980)
limit = 10;
else
limit = 5;
Last edited on
Hi Vlad, thanks for you quick response, but I tried what you suggested and I'm still getting the same error: int limit is being used without being initialized. I understand that the limit variable is local within the if and else statements, how can I get them to return their values to the main argument?
Last edited on
or if you wish to keep the limit variables local you can simply add the cout statements into the loop.
1
2
3
4
5
6
7
8
9
10
if(cyear > 1980)
{
    int limit = 10;
    cout << limit << endl;
}
else
{
    int limit = 5;
    cout << limit << endl;
}
You cannot get the same error. Please show your updated code.
// ifyear.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
int cyear;

cout << "What is the current year?" << endl;
cin >> cyear;

int limit; //---------------update

if(cyear > 1980)
int limit = 10;
else
int limit = 5;

cout << limit << endl;

system("pause");
return 0;
}
You did not update the code as I showed.

The following shall be

int limit; //---------------update

if(cyear > 1980)
limit = 10;
else
limit = 5;
Last edited on
Oh ok, looks like its working now, thank you for the help!
Topic archived. No new replies allowed.