How could I test whether the input parameter is uninitialized

Pages: 12
I have 4 arguments are integers, and for consistent reason, I want to test the input argument is initialized with a number.

How could I do this?

UPDATE:
Thank you, it is solved with answer from gunnerfunner.

Hi, thank you for your answer.

Test whether the integer is in range is not a solution for me.

Make sure the integer is initialized with zero is also not solution for me.(ZeroedPrimitive)

Imaging the 4 arguments are location of a person in real world, if one forgets to initialized one argument of all, what I get from him is for example 0, 2,2,2, so he forgets to give me the first argument. But this is a possible location, it is not out of range, and basically I can not say which location is available or not, because this depends on where is the robot and how the room, or say how world looks like. In first map, 0,2,2,2 could be legal, and if I change a map, 0,2,2,2 could be illegal.


Thank you.
Best
waschbaer

Last edited on
A good compiler will usually warn you - depending on context.

Failing that - you can't reliably tell. An uninitialised integer variable will contain garbage which may happen to be a valid integer.
Hello waschbaer,

In addition to what Chervil said you could use code to verify your variables before you call the function. This way you will know if your variables are within the proper range.

Not sure what would work best for you without seeing your code. It could be some if statements or maybe a while loop where you input.

Hope that helps,

Andy
Hello waschbaer,

What I should have mentioned is that you should always initialize your variables when you define them.

Beyond that I do not know if you are trying to use the variables as is or if there is some type of input before you pass these variables to a function. This makes a difference on how and where you could verify if the variable is good.

Hope that helps,

Andy
You could try using zeroed primitives:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template<typename T>

struct ZeroedPrimitive

{

ZeroedPrimitive() : mVal() {}

 ZeroedPrimitive(T val) : mVal(val) {}

 T mVal;

 operator T&() { return mVal; }

 operator const T&() const { return mVal; }

};

typedef ZeroedPrimitive<int> ZeroInt;


So...

 
ZeroInt x; //x is guarnateed to be zero, but behaves exactly like normal int in every single way, even primitive type conversions seem to work with no more effort 


Last edited on
using boost::optional:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>
#include <iostream>


int main()
{
   boost::optional<int> a; 
   boost::optional<int> b = 98; 
	
   std::cout << " a: " << ( (a == boost::none) ? "empty " : "not empty " ) << "\n";

   std::cout << " b: " << ( (b == boost::none) ?   "empty " : "not empty " ); 
 
}
Last edited on
Using an uninitialized variable (other than assigning a value to it) is bug. You shouldn't handle the effect of the bug, instead remove the cause.
I have 4 arguments are integers, and for consistent reason, I want to test the input argument is initialized with a number.
An int will always have a number, you can't store anythings else in it. The question rather: "Is the value valid?" To find out you need to check.
1
2
3
4
5
6
void SomeFunc(int a, int b, int c, ind d)
{
    // check if a, b, c, d have meaningful values like so
   assert(a >= minVal && a <= maxVal);
   // same for b, c and d
}
Thank you for your solution. gunnerfunner solve this problem.
This is not a solution; it is just a gross abuse of std::experimental::optional<> / boost::optional<>

The optional contained value is a value that may or may not be present;
there is no guarantee that the contained value, if present, must be an initialised value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <experimental/optional>

void foo( std::experimental::optional<int> arg = {} )
{
    if( arg == std::experimental::nullopt )
        std::cout << "optional argument was not passed\n" ;
    else std::cout << "arg == " << *arg << '\n' ;
}

int main()
{
    foo() ; // optional argument was not passed

    int i = 72; // holds an initialised value
    foo(i) ; // fine

    int j ; // holds an uninitialised value
    foo(j) ; // undefined behaviour
}



If tool support is required to detect uninitialised values, compile at high warning levels and use static analysis and/or dynamic analysis tools.

For instance, Microsoft compiler with -W4 -analyze -RTCsu and CoreGudelines checks enabled:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

void foo( int arg ) { std::cout << "arg == " << arg << '\n' ; }

int main()
{
    int i = 72; // holds an initialised value
    foo( i ) ; // fine

    int j ; // holds an uninitialised value
    foo( j ) ; // undefined behaviour
}

Warnings:
(11): warning C4700: uninitialized local variable 'j' used
(11): warning C6001: Using uninitialized memory 'j'
(7): warning C26496: Variable 'i' is assigned only once, mark it as const.
(10): warning C26494: Variable 'j' is uninitialized. Always initialize an object.

Run-time (debug): break at line #11 with
Exception Thrown
Run-Time Check Failure #3 - The variable 'j' is being used without being initialized.
there is no guarantee that the contained value, if present, must be an initialised value


neither is it clear from the programs following above comment that contained values therein are initialized. All that can be said is about non-initialized values
Well... I am a beginner level, std::experimental::optional<int> arg = {} and arg == std::experimental::nullopt is hard for me to understand, but I will have a try. I actually do not know what <experimental/optional> provides.
Perhaps, rather than looking for a technical solution at this stage, it might be worthwhile to clarify what is the problem you are trying to solve.

waschbaer wrote:
Imaging the 4 arguments are location of a person in real world, if one forgets to initialized one argument of all, what I get from him is for example 0, 2,2,2, so he forgets to give me the first argument. But this is a possible location, it is not out of range, and basically I can not say which location is available or not, because this depends on where is the robot and how the room, or say how world looks like. In first map, 0,2,2,2 could be legal, and if I change a map, 0,2,2,2 could be illegal.


In the above scenario, who is the person who 'forgets' to initialise one or more argument? Is it the programmer who writes code with defects? Or is it an end-user, who might supply invalid or incomplete input? Or perhaps the values are read from a file, which may contain incomplete or invalid values?

The solutions in each of these situations could each require a different approach.
waschbaer wrote:
basically I can not say which location is available or not [...] In first map, 0,2,2,2 could be legal, and if I change a map, 0,2,2,2 could be illegal
Chervil wrote:
what is the problem [...] who is the person who 'forgets' to initialise one or more argument?

Hi, waschbaer.
Reading this thread I learnt about optional<> and zeroed primitives, which I didn’t know, so I’m grateful to whom introduced and discussed them. But I’m a beginner too and I would also hesitate to start using an unknown feature all at once. That’s why I think I would take Chervil’s advice and consider if I can improve my software design.

What I can understand of your problem is that you need to determine if the user, somehow, succeeded in giving you 4 integer numbers or not. Later, you check if they are ‘legal’ in your map. Honestly, it’s hard to belive your code is so complicated you can’t discover if you got or not 4 numbers by the user.
What I can understand of your problem is that you need to determine if the user, somehow, succeeded in giving you 4 integer numbers or not. Later, you check if they are ‘legal’ in your map.

Important point there. Break the problem into smaller, simpler pieces.

Do I have 4 integers?

AND

Are these 4 integers a valid location?

Are two independent questions to be resolved separately.
> I have 4 arguments are integers, and for consistent reason,
> I want to test the input argument is initialized with a number.

Repeat: There is no good or fool-proof way of checking this at run-time.

The asinine idea of wrapping the integer in a class like boost::optional<> fails for a very obvious reason: how do we know that the integer that was used to construct the class was initialised? We can safely ignore any form of optional<> as a possible candidate solution.


Repeat: If tool support is required to detect uninitialised values, compile at high warning levels and use static analysis and/or dynamic analysis tools.

A code review would also obviously help.
The asinine idea of wrapping the integer in a class like boost::optional<>


I was wondering how long it'd take the 'great' JLBorges to revert to uncouth, gratuitous attacks involving his/her favorite word 'asinine' thereby once again demonstrating the emotional maturity of a toddler. More previous below:

http://www.cplusplus.com/forum/general/216925/#msg1004426

Demonstrates a very fragile ego, query anything from him/her on C++ and rudeness/unpleasantness comes your way, shower praise and all is well
In a case like this you can also use something like this:

f <- function(p1, p2 = p1 ^ 2) {
p1-p2
}

C language Training in CETPA
Hm, I misunderstood what the problem of the OP was.

optional is indeed the way to go.

JLBorges wrote:
how do we know that the integer that was used to construct the class was initialised?
? the integer that was used to construct the class?

optional of course provides several ways to detect wether or not the variable is initialized.
> ? the integer that was used to construct the class?
> ! optional of course provides several ways to detect wether or not the variable is initialized. !

!!! yes! the integer that was used to construct the class !!!

I would be delighted (and eternally grateful to you) if you can teach me how I can detect whether the contained value in optional, if present, is an initialised value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <boost/optional.hpp>

void foo( boost::optional<int> arg )
{
   std::cout << std::boolalpha << "does arg hold an initialised integer value? "
             /* << what do you want me to do here? */ << '\n' ;
}

int main()
{
    int i ; // i is uninitialised
    foo(i) ; // how does foo detect that the integer is uninitialised?

    int a[5] {} ;
    foo( a[-1] ) ; // how does foo detect that this is undefined behaviour?
}



> optional is indeed the way to go.

From my, (admittedly poor and limited) understanding, the purpose of optional is to provide a facility by which a programmer can specify that a value that may or may not be present. That is, void foo( boost::optional<int> arg ) may be called without specifying a contained integer value.

AFAIK, it provides no mechanism to ensure that:
a. the function must be called with an integer argument (a contained value must be present)
b. that contained value is a value that has been correctly initialised.

As I see it, the futile attempt to use optional to achieve this purpose is asinine.
Pages: 12