0

I have a problem with understanding this code, especially the "vet-1" part. What does it mean? What item of the array does it return? Thanks

#include <stdlib>
#include <iostream>

using namespace std;

void change( int m, int n[7]);

int main(){
int vet[] = {1,2,3,4,5};
change(vet[4],vet-1);
change(0,&vet[4]);
int i=0;
for (i=0;i<5;i++) cout << vet[i];
return 0;
}

void change( int m, int n[7]) {
(*(n+m))--; m++; n--;
}
Giulio Mattolin
  • 554
  • 2
  • 12
  • 2
    I think it is UB as `vet-1` is out of bound array (even if not deferenced). – Jarod42 Jun 07 '18 at 09:50
  • btw afaik C has no iostream header nor a namespace std – 463035818_is_not_a_number Jun 07 '18 at 09:50
  • @Jarod42: Yes your're correct. The only exception would be `vet + 5`. – Bathsheba Jun 07 '18 at 09:51
  • It probably tries to use the fact that with C arrays [`a[b]` is the same as `*(a + b)`](https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a), but fails by going out of bounds. – Bo Persson Jun 07 '18 at 09:54
  • That won't even compile due to syntax errors – Killzone Kid Jun 07 '18 at 09:58
  • In general, subtracting one from a pointer is analogous to adding one to a pointer: it moves to the element just before. If the pointer points somewhere within an array, this can be perfectly legal and perfectly meaningful; it's a problem only if the pointer is already pointing at the beginning of the array. In the posted code fragment, however, `v` does point to the beginning of the array (it *is* the array!), so it's undefined. The code has other problems, and should be thrown away, not learned from. Any textbook or course that presented this code for instruction is suspect. – Steve Summit Jun 07 '18 at 09:59

1 Answers1

11

vet - 1 is an attempt at referring to the pointer to the element just before vet[0].

Actually the behaviour on doing that is undefined. So the entire program is undefined.

Nothing to understand here; move on!

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
  • 4
    _"move on!"_ quite literally. Especially if it was an interview question. – YSC Jun 07 '18 at 09:52
  • I thought the same, but why the program print something instead of giving a run-time error? – Giulio Mattolin Jun 07 '18 at 13:10
  • 1
    @FrancescoMarzetta: Because when you use `[]` to access an element, C++ assumes you know what you're doing. If you want an exception to be thrown, then use `.at`. – Bathsheba Jun 07 '18 at 13:12
  • 2
    @FrancescoMarzetta That's part of undefined behavior. The program *might* crash, but it doesn't have to. – dbush Jun 07 '18 at 13:12