2

I have the following legacy code:

unsigned int code = 'abcd';

I need to add one character to the above code:

unsigned int code = 'abcd2';

but then I get the following error: too many characters in character constant. Why using unsigned long int type doesn't resolve that issue ? Is it possible to fix it or I should modify the code and use a char array ?

12
  • I know but that's a legacy code which compiles.
    – Irbis
    Sep 17, 2020 at 9:50
  • 1
    @kiranBiradar in C multi-character literals are legal. Their value is implementation defined. Not sure about C++
    – Gerhardh
    Sep 17, 2020 at 9:50
  • 1
    You mention C++ but added C and C++. Which language do you use?
    – Gerhardh
    Sep 17, 2020 at 9:51
  • 1
    You might start with printing the result of that assignment. What is the value of that literal? The C standard defines that the value of this is implementation defined. Any compiler vendor can do what they want. E.g. they could just use first char and drop the rest. Or only the last char. Or the could tread as 4 bytes. Whatever they like. How could this possible be portable? If a string was meant, what is the value? Should it be handled as a hex digit? A set of 4 8bit values? Try to get rid of that thing. Fast! ;)
    – Gerhardh
    Sep 17, 2020 at 10:02
  • 1
    C11: 6.4.4; 10 ... The value of an integer character constant containing more than one character (e.g., 'ab'), or ..., is implementation-defined
    – Gerhardh
    Sep 17, 2020 at 10:10

1 Answer 1

7

Why using unsigned long int type doesn't resolve that issue ?

Because the type of the variable has no effect on the type of the literal. The type of multi-char literal is int. There are no unsigned long multi-char literals.

Also, on some systems unsigned long has exactly as many bytes as int has.

Is it possible to fix it

There is no way to fit more characters in multi-char literal.

or I should modify the code and use a char array ?

If you need more characters, then yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.