2

When I have to use size_t, can I use such expressions?

/* size_ is size_t type and has some value*/

and I want to change the value like ++size_; or --size_;

And I also want to make array using size_t like

array[size_]=something;

Are they valid?

Kim
  • 23
  • 3
  • `size_t` is an unsigned integer type, so all of them are valid. – MikeCAT Sep 26 '20 at 05:42
  • Is this what you're asking? [How to dynamically allocate arrays in C++](https://stackoverflow.com/questions/35532427/how-to-dynamically-allocate-arrays-in-c) –  Sep 26 '20 at 05:44
  • `array[size_]=something;` assigns to an array element, it doesn't create a new array – Alan Birtles Sep 26 '20 at 09:01

1 Answers1

2

Yes, you can use all of them because size_t is an unsigned integer type.

Example:

#include <iostream>

int main(void) {
    size_t size_ = 0;
    int array[10] = {0};
    int something = 42;

    std::cout << "initial: " << size_ << std::endl;

    ++size_;

    std::cout << "incremented: " << size_ << std::endl;

    --size_;

    std::cout << "decremented: " << size_ << std::endl;

    array[size_]=something;

    std::cout << "array: " << array[0] << std::endl;

    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70