-1

I'm not a C++ developer but found my self doing this. What does r in the following code example represents, and what is the c# code equivalent?

#include <iostream>

using namespace std;

int main()
{
    cout<<"Value:\n";

    uint32_t k[62];
    uint32_t* r = k;
    *r++;

    cout<<*r;
    
    return 0;
}
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
peter bence
  • 782
  • 3
  • 14
  • 34
  • Do not tag both C and C++ except when asking about differences or interactions between the two languages. – Eric Postpischil Mar 09 '21 at 11:56
  • @jason.kaisersmith I think the C# tag was valid, given OP is asking for the C# equivalent of this code? – canton7 Mar 09 '21 at 11:57
  • 1
    @canton7 Yes sorry, I meant to remove the C Tag and seem to have clicked the wrong one!. – jason.kaisersmith Mar 09 '21 at 11:59
  • 1
    The question should be, why are you doing it like you are doing it here? Maybe that could help to elaborate why you (maybe) need to do it and what the difference to C# is. The code snippet itself right now is not useful – RoQuOTriX Mar 09 '21 at 11:59
  • 1
    Wanting readers to explain to you why you are doing something makes for a tricky question... What problem were you trying to solve, what gave you the idea to write this code, and does it seem to solve it? – underscore_d Mar 09 '21 at 12:02

1 Answers1

1

uint32_t* r = k; makes r point to the first element of the uninitialized array k.

*r++; increments r to point to the second element of k, and then dereferences the value of the second element (which is undefined). The deference is a no-op because the result is not used, so the statement does the same as just r++;. (*r)++; would increment the array element.

cout<<*r; then prints the value of the second element of k, which causes undefined behavior because the value is not defined.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • 1
    Is it really undefined behavior? It's a primitive after all, so it will print undefined data, but the operation itself is still well defined, isn't it? It's not dereferencing an unitialized pointer, which indeed can result in undefined behavior. – Devolus Mar 09 '21 at 12:38
  • Agree with Devolus, I dont think it's an undef behavior: something is printed for sure, just the output value is unknown – Mauro Dorni Mar 09 '21 at 12:54
  • 1
    @Devolus I'm pretty sure it's UB, see e.g. https://stackoverflow.com/q/49696810/3425536: "If an indeterminate value is produced by an evaluation, the behavior is undefined [...]" – Emil Laine Mar 09 '21 at 13:41