manipulating c variable via inline assembly [duplicate]

Solution 1:

The asm() function follows this order:

asm ( "assembly code"
           : output operands                  /* optional */
           : input operands                   /* optional */
           : list of clobbered registers      /* optional */
);

and to put 11 to x with assembly via your c code:

int main()
{
    int x = 1;

    asm ("movl %1, %%eax;"
         "movl %%eax, %0;"
         :"=r"(x) /* x is output operand and it's related to %0 */
         :"r"(11)  /* 11 is input operand and it's related to %1 */
         :"%eax"); /* %eax is clobbered register */

   printf("Hello x = %d\n", x);
}

You can simplify the above asm code by avoiding the clobbered register

asm ("movl %1, %0;"
    :"=r"(x) /* related to %0*/
    :"r"(11) /* related to %1*/
    :);

You can simplify more by avoiding the input operand and by using local constant value from asm instead from c:

asm ("movl $11, %0;" /* $11 is the value 11 to assign to %0 (related to x)*/
    :"=r"(x) /* %0 is related x */
    :
    :);

Another example: compare 2 numbers with assembly