3

I saw a "puzzle", where you have to write a function in C that returns the value of a+c, however, you can't use the + operator.

unsigned f(unsigned a, unsigned c) {
    return <write your coe here>;
}

You can use only the following characters: harc()&|[]*/.

klenium
  • 2,468
  • 2
  • 24
  • 47

1 Answers1

5

This should work in practice, though I believe it relies on undefined behaviour and will generate warnings:

unsigned f(unsigned a, unsigned c) {
    return &(((char*)a)[c]);
}

(fewer brackets are necessary in practice)

This works as follows:

   (char*)a      - cast 'a' to a 'char *' pointer 
  ((char*)a)[c]  - treat 'a' as an array, and index the c'th element, which
                   will be at address c + a
&(((char*)a)[c]) - take the address of that element, i.e. c + a

Finally the return casts this back to unsigned.

Trivial test harness which compiles with gcc 4.8 with two warnings:

#include <stdio.h>

unsigned
f (unsigned a, unsigned c)
{
  return &(((char *) a)[c]);
}

int
main (int argc, char **argv)
{
  unsigned a = 1;
  unsigned b = 2;
  unsigned c = f (a, b);
  printf ("%d + %d = %d\n", a, b, c);
  return 0;
}

Note as this is C, not C++, it may not compile with a C++ compiler.

Crowman
  • 25,242
  • 5
  • 48
  • 56
abligh
  • 24,573
  • 4
  • 47
  • 84
  • 1
    Awesome! And can you explain why it works/what's happening? – klenium Jan 02 '16 at 13:30
  • 2
    `error: invalid conversion from 'char*' to 'unsigned int'` is what I get – Ziezi Jan 02 '16 at 13:31
  • @simplicisveritatis - g++ 4.7.something vomits this error message, while gcc 4.7.sameSomething turns it into working code. – enhzflep Jan 02 '16 at 13:35
  • 1
    @simplicisveritatis Compiles file here with gcc 4.8 (albeit with two warnings) and works. Compiling with g++ won't work as g++ compiles C++ and this is C. – abligh Jan 02 '16 at 13:36
  • Just cured it using `reinterpret_cast` if you want add it to your answer. Ugly, but it works ! :) – Ziezi Jan 02 '16 at 13:38
  • @simplicisveritatis no, that would not be OK as most of the characters in `reinterpret_cast` are not permitted. This is a C challenge, not a C++ challenge, and `reinterpret_cast` is not valid C. C and C++ are different (albeit related) languages. – abligh Jan 02 '16 at 13:39
  • @simplicisveritatis, no, that would not be OK either as none of the characters `i`, `n` or `t` are permitted. – abligh Jan 02 '16 at 13:41
  • actually, the posted answer compiles with 4 warnings, 1) unused parameter `argc` 2) unused parameter `argv` 3) line 6 cast to pointer to integer of different size 4) return makes integer from pointer without a cast – user3629249 Jan 04 '16 at 06:39
  • suggest changing the signature of the main() function to: `int main( void )` – user3629249 Jan 04 '16 at 06:40