3

I have my class Stack

class Stack
{
public:
    Stack(unsigned int Size)
   {
    size = Size;
   }

private:
    unsigned int size;
    void* Block;
};

int _tmain(int argc, _TCHAR* argv[])
{
    Stack x(-1);
    return 0;
}

I want to make sure that even I pass negative value to the constructor argument that the object wont be constructed , but when I'm giving -1 value , it's accepting it and the variable size value is 4294967295 , which is the same -1 after removing the sing bit as far as I know ...

so how I shall handle this situation ? shall I throw exception ? or just make to take default value in case of wrong value ?

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
Alphas Supremum
  • 435
  • 3
  • 17
  • 2
    Depending on your compiler, you can at least get [compilation warnings](https://stackoverflow.com/questions/765709/why-compiler-is-not-giving-error-when-signed-value-is-assigned-to-unsigned-integ) for passing signed values as an unsigned parameter. As far as at runtime.... you might be SOL, because that behavior is [specified by the standard](https://stackoverflow.com/questions/2711522/what-happens-if-i-assign-a-negative-value-to-an-unsigned-variable) – Cory Kramer Oct 01 '15 at 17:46
  • Use the "try catch" handler in your _tmain function and throw an exception in your class constructor. Check http://www.cplusplus.com/doc/tutorial/exceptions/ – ahPo Oct 01 '15 at 17:47
  • 1
    @user2340218 Catch what? There will be no exception to catch. – Cory Kramer Oct 01 '15 at 17:47
  • 1
    Do nothing and do not fight stupid programmers. A crash is a viable result in this case. –  Oct 01 '15 at 17:52

2 Answers2

1

If you are using the Visual C++ compiler (MSVC), as a general rule, you may want to compile your code at /W4 (i.e. warning level 4), so the compiler speaks up more frequently, and helps identifying programmer's mistakes.

For example:

C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp

warning C4245: 'argument' : conversion from 'int' to 'unsigned int',
signed/unsigned mismatch

EDIT

In addition, you may want to mark your constructor explicit, to avoid implicit bogus conversions from integers to instances of your Stack class.

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
0

I want to make sure that even I pass negative value to the constructor argument that the object wont be constructed

One way to do this is -Wsign-conversion -Werror

$ clang++ -Werror -Wsign-conversion -c stack.cpp
stack.cpp:18:13: error: implicit conversion changes signedness: 'int' to 'unsigned int' [-Werror,-Wsign-conversion]
    Stack x(-1);
          ~ ^~
1 error generated.


$ cat stack.cpp

class Stack
{
    public:
        Stack(unsigned int Size)
        {
            size = Size;
        }

    private:
        unsigned int size;
        void* Block;
};

typedef const char _TCHAR;
int _tmain(int argc, _TCHAR* argv[])
{
    Stack x(-1);
    return 0;
}
Brian Cain
  • 14,403
  • 3
  • 50
  • 88