Why can we use only four operators (+,-,++,--) in pointer arithmetic? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Why can we use only four operators (+, -, ++, --) in pointer arithmetic? Does it have any relation with inbuilt hardware since it is dealing with addresses?
Since an array uses relative addressing, in that we increment the address to perform that operation, I think this might be one of the reasons for using those 4 operators alone.

Why can we use only four operators (+, -, ++, --) in pointer arithmetic?
Because the language was built that way. The most common operation is iteration, which is probably why those operators are allowed.
As for rationales behind why the C language was designed this way, there's not much to be found. I checked the C99 rationale regarding pointer arithmetic, but it is mostly concerned about the result of pointer arithmetic overflowing and does not mention why/when pointer arithmetic makes sense.
Does it have any relation with inbuilt hardware since it is dealing with addresses?
No, it has nothing to do with that. Addresses are just numbers. You can always cast any pointer to uintptr_t and then use it as any other integer.

You can use any operator, as long as the result will be int. For example:
int A[10], i=5;
int *p;
p = A + (i/2);

Simple because C was designed that way.
+,- can be simply used to add or subtract two pointers respectively (value at address only). While on the other hand increment and decrement operators i.e ++ and -- can be used to increment or decrement the pointer.Remember the data type of pointer plays an important role in these two(++,--) operators.
For example if you define an pointer of type *int then ++ will increment the memory address by 2 (since the size of int in most compilers is 2 ) and so same is with the -- operator as it will decrease it by a 2.

Related

Evaluation of expression in printf function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Please have a look at below code
#include<stdio.h>
int main(void){
int *ptr,a,b;
a = ptr;
b = ptr + 1;
printf("the value of a,b is %d and %d respectively\n",a,b);
printf("the value of a is %d \n",(ptr));
printf("the value of b is %d \n",(ptr+1));
printf("the value of (ptr+1)-ptr is %d \n",(ptr+1)-ptr);
return 0;
}
Output:
the value of a,b is 0 and 4 respectively
the value of a is 0
the value of b is 4
the value of (ptr+1)-ptr is 1
I am not able to understand why the value of (ptr+1)-ptr is 1 not 4 as 4-0?Is it due to computation optimization?
First of all, what you did is wrong. Pointer arithmetic is valid if both of them point to elements of the same array object or one past the last element of the array object. So it is undefined behavior.
In your case, the subtraction returns how far one is from the other - based on the type of the object pointed to which is int here, and sizeof int being 4 bytes, it returned 1 denoting the 1 int separation. (meaning the same as 4 byte - as can be inferred from the value of a and b).
From §6.5.6¶9 C11 standard (this points out both the points mentioned above)
When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements...
And you are printing addresses with %d format specifier. You should use %p format specifier with argument void* casted. And never think of dereferencing these pointers as it would be Undefined Behavior to do so.
I am not able to understand why the value of (ptr+1)-ptr is 1 not 4
No, pointer arithmetic in C happens in units related to the pointed type (not in bytes). Read some C programming book.
So (ptr+1) - ptr is 1, but if you cast each pointer to a char*, e.g. by coding (char*)(ptr-1) - (char*)ptr, you'll get probably 4 (assuming sizeof(int) is 4).
Don't forget to enable all warnings and debug info when compiling: if using GCC, compile with gcc -Wall -Wextra -g, then improve your code to get no warnings at all. Read more about undefined behavior (your code have some) and be scared of it. Use the gdb debugger (or whatever other debugger you can use). Read documentation of every standard function that you are using (and of every external function from some other library), notably of printf.
Later, consider also reading pieces of the C11 standard, e.g. n1570 (a draft which is actually the standard text).
Care about portability (to different computers or compilers).
By definition, compiler optimization should not change the observed behavior and semantics of your program.

Why does the following code yield O/P as 3 and not 6? [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 5 years ago.
Why doesn't the value of x increment in the following code?
#include <stdio.h>
int main(){
int x = 3, i = 0;
do {
x = x++;
i++;
} while (i != 3);
printf("%d\n", x);
}
In x = x++, you are saying both to increment x and to assign x a value. The C standard does not define what happens if you do both of these things “at the same time.” For this purpose, “at the same time” means your code has not arranged for one of them to occur before the other.
If you put the increment and the assignment in separate statements, the C standard says that one of them occurs before the other, and then the behavior is fully defined. Technically, there is a sequence point between two such statements. Sequence points are barriers that separate effects. Inside the single statement x = x++, there is no sequence point.
(There is more about sequence points and sequencing in C, but the details are beyond the scope of this question.)
In the simplest C implementation, the compiler might treat x = x++; as if it were x = x; x++; or as if it where int Temporary = x; x++; x = Temporary;. The first would set x to 3 and then to 4. The second would set x to 4 and then to 3. However, the C standard gives implementations a great deal of latitude. In some C implementations, integer types might be made up of parts—a small computer might not be able to handle 32-bit integers all at once, so it might have to do arithmetic in multiple 16-bit steps, or even multiple 8-bit steps. The C standard says, since you have not arranged for the assignment and the increment to occur in a particular order, then, not only is the implementation allowed to do them in either order, it is even allowed to mix the steps. It might do one byte of the assignment, one byte of the increment, the second byte of the assignment, the second byte of the increment, the third byte of the increment, the third byte of the assignment, and so on. In general, you could get a nonsensical answer that is a mishmash of operations on the parts.
So the C standard does not say that, if you do not arrange for the operations to be ordered, then either one happens before the other. It says, if you do not arrange for the operations to be ordered, we do not guarantee what will happen at all. You may get a big mess.

Bitwise & evaluation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
For the below sample code:
// Note that a, b, c and d can have value of 0 or 1 only
int isAllTrue(int a, int b, int c, int d)
{
return (a && b && c && d);
// THIS ALSO RETURNS CORRECT VALUE
// return (a & b & c & d);
}
If we know that operands can be either 0 or 1, which operation would be preferable from performance point of view: bitwise or logical? Does it really matter?
Does evaluation stop in the case of bitwise "&" when the operand is 0 ?
Use & for bit operations. Use && for logical operations. If you use a bitwise operation where you should use a logical operation or vice versa, the reader will (a) be confused, (b) check very carefully if your code has introduced a subtle bug.
Programming relies on idioms. If your code doesn't match the expected idiom, then you must have a good reason, and you should write a comment explaining why.
It doesn't matter which formulation you use, with active compiler optimization, all shown evaluations should already be completed at compile time.
As for your last question, the bitwise operators do not employ shortcut evaluation and thus always evaluate each operand.
there seems to be a lot of confusion about questions like this one ... and a lot of wrong answers. Well, here are the facts for C/C++ :
&&, || and ! are logical operators, they test for
boolean expressions - integral values (numbers) are considered true if their value is not zero, false otherwise -
no matter how many numbers you check for but 0 && 1 will be evaluated to false, for instance because of the first 0 -- it could be re-written as false && true
&, |, ~, ^, >>, << are bitwise operators, they mask/assign
bit patterns of integral values, you can do a lot of cool calculations like that - but you really need to know how numbers are represented inside of your CPU before you start doing that.
Conclusion : your question doesnt make sense - because you thought that these operators are similar .... they arent.

right shifting the double variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
hi I want to do the followed task:
double time;
char array[6];
for(int index=0; index<6; index++){
array[index]=(char)(time>>(8*index));
}
but the error appears: expresion must have integral or unscoped enum
From ISO/IEC 9899:1999 (a.k.a. C99 standard):
6.5.7 Bitwise shift operators
Constraints
2 Each of the operands shall have integer type.
If you want to divide time by 2 to the power of (8*index), you can either:
Use pow() from math.h, or
Create an integer variable with value 1 << (8*index), then divide time by this variable
If you want to actually do a bit shift of the binary representation of the IEEE floating point number(1) (not that I understand why you would want to do that), you can do the following:
uint64_t x = *(uint64_t *)&time;
array[index]=(char)(x>>(8*index));
(1): Assuming your implementation uses IEEE floating point
Right shifting a float or double is almost certainly not what you meant to do, as the data representation is not one that would be affected by right shift as division by a power of 2.
You cannot use right-shifting operator for double variable.

Is the assignment expression after "sizeof" never executed? [duplicate]

This question already has answers here:
Why does sizeof(x++) not increment x?
(10 answers)
Closed 9 years ago.
e.g.
int a = 3;
int b = sizeof(++a);
int c = a;
Is c equal to 3 or 4 as the result?
Does the result depend on the specific compiler?
The specification states that the increment operator does NOT take affect when used within a sizeof operator.
This also makes sense from an abstract viewpoint. Specifically, the sizeof operator returns the number of bytes used by an object. While incrementing an integer or even a pointer does NOT change the size of that integer, the ++ operator would mis-lead a new programmer into thinking the size does change.
If interested look-up the topic "side-effects" for more discussion about this subject.

Resources