First, your need to know What is the difference between ++i and i++?.
In your case, you want to:
- read your
data
at head
- move your
head
- return the value read in 1.
So, in code it looks like that:
char testclass::read() {
char result = data[head]; // 1
head += 1; // 2
return result; // 3
}
Now, you can use ++head
or head++
instead of head += 1
here. It won't change the behaviour of your function because the result of this statement is not used (i.e. you can do x = y += 1;
but probably don't want to.)
If you want, you can make write this function in one line, but will lose in readability (it's often better to have only one statement by line, it's less error-prone this way):
return data[head++];
This works because head++
increment the variable but return its "old" value.
But don't think it's faster that the three-line code: your compiler is clever enough to optimize that and will most probably generate the same assembly code for both implementation.
Regarding your first version of the function, don't forget that code after a return statement are not executed. (See for example this SO Execution of code in a function after the return statement has been accessed in c++)