0
char short_string[] = "abc"   
char short_string[] = {'a', 'b', 'c'}   

what I think is the difference is that the 2nd line is a switch statement and that it requires input from user (either a b or c as the 1st line is more of a statement.... is this right ?

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
anonomys
  • 29
  • 2

3 Answers3

9

No. That's not a switch statement. Both lines are variable declarations with initialization. The difference is that:

char short_string[] = "abc"

Declares short_string null terminated c-string.
Memory dump: 0x61, 0x62, 0x63, 0x00
Variable length in bytes: 4

While second line:

char short_string[] = {'a', 'b', 'c'}

Declares short_string as byte array.
Memory dump: 0x61, 0x62, 0x63
Variable length in bytes: 3

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
0

The first statement declares and initializes a string with the content abc (including terminating zero) -- this is a character array that is four characters long.

The second statement declares a character array with the three characters a, b and c -- it's almost the same thing as the first, except no terminating zero (not a proper string).

Also: All statements in C/C++ must be terminated with a semicolon.

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
0

The difference is the first option will assign three characters and a trailing null ( x'00') the second option will assign the same three characters but no trailing null and would cause problems were you attempt to use any of the str.... family of functions.

James Anderson
  • 27,109
  • 7
  • 50
  • 78