Difference between using " and ' in C [duplicate] - c

This question already has answers here:
Single quotes vs. double quotes in C or C++
(15 answers)
Closed 1 year ago.
I tried running a C program with the code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char grade;
float mark;
printf("Enter total mark percentage : ");
scanf("%f", &mark);
if(mark>=90){
grade="A";
}else{
grade="B";
}
printf("Your grade is %c", grade);
return EXIT_SUCCESS;
}
It produces a warning 'assignment from 'char' to 'char*' makes integer from pointer without a cast'.
I am able to solve it by changing " to ' in line 10 and 12
grade='A';
}else{
grade='B';
}
This solves the warning. But I want to use " to contain A & B.
I tried initializing mark, as int instead of char in line 5 but it also didn't work.
I just want to know what is the difference in using ' and " .

The symbol ' is used to specify an integer character constant. For example 'A' is an integer character constant that has the type int.
The symbol " is used to specify a string literal. For example "A" is a string literal that has the type char[2]. That is the string literal is a character array that is stored like
{ 'A', '\0' }
String literals contain sequences of characters terminated by the zero terminating character '\0' that also is stored in string literals.
Character arrays designators used in expressions are implicitly (with rare exceptions) converted to pointers to their first elements of the type char * or const char *.
This means that in this assignment statement
grade="A";
the string literal "A" that has the array type char[2] is converted to a pointer to its first element 'A'. As a result the compiler issues a message that you are trying to assign a pointer to an object of an integer type.
You can write for example
grade = "A"[0];
or
grade = *"A";
But this will only confuse readers of the code because it will be more simpler and clear to write
grade = 'A';
That is there is no need to use a whole array like "A" (remember that it internally represents an array of two elements { 'A', '\0' }) to use only its one element 'A'.

"..." is used for strings - ie. a NUL-terminated char-array (char[] or char*)
'.' is used for a single character - ie. a char.
For example:
"Hello" is a string (char-array) with the following 6 single characters:
'H', 'e', 'l', 'l', 'o', '\0' (The last is the NUL-character).
Thus
'A' is just 'A' (a single char containing the ASCII-value for A)
while
"A" is a char array, containing two chars - 'A' and '\0' (and thus a string)

" " are used for string and ' ' is used for the character. as A and B are
characters we will use single quotes for them.
this is why this format is correct.
grade='A';
}else{
grade='B';
}

Related

What double quotes and single quote makes difference in %c? [duplicate]

When should I use single quotes and double quotes in C or C++ programming?
In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array).
In C++ the type of a character literal is char, but note that in C, the type of a character literal is int, that is sizeof 'a' is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), while sizeof(char) is 1 everywhere.
Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:
6.4.4.4p10: "The value of an integer character constant containing more
than one character (e.g., 'ab'), or
containing a character or escape
sequence that does not map to a
single-byte execution character, is
implementation-defined."
This could look like this, for instance:
const uint32_t png_ihdr = 'IHDR';
The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.
Single quotes are characters (char), double quotes are null-terminated strings (char *).
char c = 'x';
char *s = "Hello World";
'x' is an integer, representing the numerical value of the
letter x in the machine’s character set
"x" is an array of characters, two characters long,
consisting of ‘x’ followed by ‘\0’
I was poking around stuff like: int cc = 'cc'; It happens that it's basically a byte-wise copy to an integer. Hence the way to look at it is that 'cc' which is basically 2 c's are copied to lower 2 bytes of the integer cc. If you are looking for a trivia, then
printf("%d %d", 'c', 'cc'); would give:
99 25443
that's because 25443 = 99 + 256*99
So 'cc' is a multi-character constant and not a string.
Cheers
Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.
char myChar = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };
single quote is for character;
double quote is for string.
In C, single-quotes such as 'a' indicate character constants whereas "a" is an array of characters, always terminated with the \0 character
Double quotes are for string literals, e.g.:
char str[] = "Hello world";
Single quotes are for single character literals, e.g.:
char c = 'x';
EDIT As David stated in another answer, the type of a character literal is int.
A single quote is used for character, while double quotes are used for strings.
For example...
printf("%c \n",'a');
printf("%s","Hello World");
Output
a
Hello World
If you used these in vice versa case and used a single quote for string and double quotes for a character, this will be the result:
printf("%c \n","a");
printf("%s",'Hello World');
output :
For the first line. You will get a garbage value or unexpected value or you may get an output like this:
�
While for the second statement, you will see nothing. One more thing, if you have more statements after this, they will also give you no result.
Note: PHP language gives you the flexibility to use single and double-quotes easily.
Use single quote with single char as:
char ch = 'a';
here 'a' is a char constant and is equal to the ASCII value of char a.
Use double quote with strings as:
char str[] = "foo";
here "foo" is a string literal.
Its okay to use "a" but its not okay to use 'foo'
Single quotes are denoting a char, double denote a string.
In Java, it is also the same.
While I'm sure this doesn't answer what the original asker asked, in case you end up here looking for single quote in literal integers like I have...
C++14 added the ability to add single quotes (') in the middle of number literals to add some visual grouping to the numbers.
constexpr int oneBillion = 1'000'000'000;
constexpr int binary = 0b1010'0101;
constexpr int hex = 0x12'34'5678;
constexpr double pi = 3.1415926535'8979323846'2643383279'5028841971'6939937510;
In C & C++ single quotes is known as a character ('a') whereas double quotes is know as a string ("Hello"). The difference is that a character can store anything but only one alphabet/number etc. A string can store anything.
But also remember that there is a difference between '1' and 1.
If you type
cout<<'1'<<endl<<1;
The output would be the same, but not in this case:
cout<<int('1')<<endl<<int(1);
This time the first line would be 48. As when you convert a character to an int it converts to its ascii and the ascii for '1' is 48.
Same, if you do:
string s="Hi";
s+=48; //This will add "1" to the string
s+="1"; This will also add "1" to the string
different way to declare a char / string
char char_simple = 'a'; // bytes 1 : -128 to 127 or 0 to 255
signed char char_signed = 'a'; // bytes 1: -128 to 127
unsigned char char_u = 'a'; // bytes 2: 0 to 255
// double quote is for string.
char string_simple[] = "myString";
char string_simple_2[] = {'m', 'S', 't', 'r', 'i', 'n', 'g'};
char string_fixed_size[8] = "myString";
char *string_pointer = "myString";
char string_poionter_2 = *"myString";
printf("char = %ld\n", sizeof(char_simple));
printf("char_signed = %ld\n", sizeof(char_signed));
printf("char_u = %ld\n", sizeof(char_u));
printf("string_simple[] = %ld\n", sizeof(string_simple));
printf("string_simple_2[] = %ld\n", sizeof(string_simple_2));
printf("string_fixed_size[8] = %ld\n", sizeof(string_fixed_size));
printf("*string_pointer = %ld\n", sizeof(string_pointer));
printf("string_poionter_2 = %ld\n", sizeof(string_poionter_2));

Array character as parameters in c [duplicate]

When should I use single quotes and double quotes in C or C++ programming?
In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array).
In C++ the type of a character literal is char, but note that in C, the type of a character literal is int, that is sizeof 'a' is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), while sizeof(char) is 1 everywhere.
Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:
6.4.4.4p10: "The value of an integer character constant containing more
than one character (e.g., 'ab'), or
containing a character or escape
sequence that does not map to a
single-byte execution character, is
implementation-defined."
This could look like this, for instance:
const uint32_t png_ihdr = 'IHDR';
The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.
Single quotes are characters (char), double quotes are null-terminated strings (char *).
char c = 'x';
char *s = "Hello World";
'x' is an integer, representing the numerical value of the
letter x in the machine’s character set
"x" is an array of characters, two characters long,
consisting of ‘x’ followed by ‘\0’
I was poking around stuff like: int cc = 'cc'; It happens that it's basically a byte-wise copy to an integer. Hence the way to look at it is that 'cc' which is basically 2 c's are copied to lower 2 bytes of the integer cc. If you are looking for a trivia, then
printf("%d %d", 'c', 'cc'); would give:
99 25443
that's because 25443 = 99 + 256*99
So 'cc' is a multi-character constant and not a string.
Cheers
Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.
char myChar = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };
single quote is for character;
double quote is for string.
In C, single-quotes such as 'a' indicate character constants whereas "a" is an array of characters, always terminated with the \0 character
Double quotes are for string literals, e.g.:
char str[] = "Hello world";
Single quotes are for single character literals, e.g.:
char c = 'x';
EDIT As David stated in another answer, the type of a character literal is int.
A single quote is used for character, while double quotes are used for strings.
For example...
printf("%c \n",'a');
printf("%s","Hello World");
Output
a
Hello World
If you used these in vice versa case and used a single quote for string and double quotes for a character, this will be the result:
printf("%c \n","a");
printf("%s",'Hello World');
output :
For the first line. You will get a garbage value or unexpected value or you may get an output like this:
�
While for the second statement, you will see nothing. One more thing, if you have more statements after this, they will also give you no result.
Note: PHP language gives you the flexibility to use single and double-quotes easily.
Use single quote with single char as:
char ch = 'a';
here 'a' is a char constant and is equal to the ASCII value of char a.
Use double quote with strings as:
char str[] = "foo";
here "foo" is a string literal.
Its okay to use "a" but its not okay to use 'foo'
Single quotes are denoting a char, double denote a string.
In Java, it is also the same.
While I'm sure this doesn't answer what the original asker asked, in case you end up here looking for single quote in literal integers like I have...
C++14 added the ability to add single quotes (') in the middle of number literals to add some visual grouping to the numbers.
constexpr int oneBillion = 1'000'000'000;
constexpr int binary = 0b1010'0101;
constexpr int hex = 0x12'34'5678;
constexpr double pi = 3.1415926535'8979323846'2643383279'5028841971'6939937510;
In C & C++ single quotes is known as a character ('a') whereas double quotes is know as a string ("Hello"). The difference is that a character can store anything but only one alphabet/number etc. A string can store anything.
But also remember that there is a difference between '1' and 1.
If you type
cout<<'1'<<endl<<1;
The output would be the same, but not in this case:
cout<<int('1')<<endl<<int(1);
This time the first line would be 48. As when you convert a character to an int it converts to its ascii and the ascii for '1' is 48.
Same, if you do:
string s="Hi";
s+=48; //This will add "1" to the string
s+="1"; This will also add "1" to the string
different way to declare a char / string
char char_simple = 'a'; // bytes 1 : -128 to 127 or 0 to 255
signed char char_signed = 'a'; // bytes 1: -128 to 127
unsigned char char_u = 'a'; // bytes 2: 0 to 255
// double quote is for string.
char string_simple[] = "myString";
char string_simple_2[] = {'m', 'S', 't', 'r', 'i', 'n', 'g'};
char string_fixed_size[8] = "myString";
char *string_pointer = "myString";
char string_poionter_2 = *"myString";
printf("char = %ld\n", sizeof(char_simple));
printf("char_signed = %ld\n", sizeof(char_signed));
printf("char_u = %ld\n", sizeof(char_u));
printf("string_simple[] = %ld\n", sizeof(string_simple));
printf("string_simple_2[] = %ld\n", sizeof(string_simple_2));
printf("string_fixed_size[8] = %ld\n", sizeof(string_fixed_size));
printf("*string_pointer = %ld\n", sizeof(string_pointer));
printf("string_poionter_2 = %ld\n", sizeof(string_poionter_2));

What's the trailing symbols within an char array which initialized with brace-enclosed lists in clang?

#include <stdio.h>
int main(int argc, const char *argv[]) {
char name1[] = {'f','o','o'};
char name2[] = "foo";
printf("%s\n", name1);
printf("%s\n", name2);
return 0;
}
running the code above results in :
foox\363\277\357\376
foo
Program ended with exit code: 0
So, what's the difference between these 2 initializers?
name1 is an array of three characters {'f', 'o', 'o'}.
name2 is an array of four characters {'f', 'o', 'o', '\0'}.
printf("%s", ...) expects an array terminated with a null character. Because name1 isn't, you start dereferencing characters past the end of the array which can have the traditional undefined behavior.
The first array (i.e., {'f','o','o'}) will not have the null character '\0', wheres the second (i.e., "foo") will.
The printf specification when using the %s says the following:
If no l modifier is present: The const char * argument is expected to
be a pointer to an array of character type (pointer to a string).
Characters from the array are written up to (but not including) a
terminating null byte ('\0'); if a precision is specified, no more
than the number specified are written. If a precision is given, no
null byte need be present; if the precision is not specified, or is
greater than the size of the array, the array must contain a
terminating null byte.
Since, your printf did not include the precision, it will write up characters from the array until reaching the null byte ('\0'). Consequently, in the case of the char name1[] = {'f','o','o'}; resulting in the printf write up characters out of the memory that was allocated for the name1 array. Such behaviour is considered to be undefined.
This is the reason why printf("%s\n", name1); prints foo plus some extra symbols from the next positions in memory that should not have been accessed, whereas with printf("%s\n", name2); it prints exactly the string "foo" as it is.
There are no trailing symbols in the array.
But printf’s %s format expects a string, and the array name1 isn’t a string: by definition, C strings are zero terminated … and your array isn’t. So the behaviour is undefined, and what seems to happen in your particular case is that printf continues printing random values that happen to be in memory just behind the contents of name1.
In C language if you are initializing string with character by character initializer you need to put '\0' which is NULL/terminating character to indicate the end of string.
so name1 should be {'f', 'o', 'o', '\0'}
x\363\277\357\376 that you can see at the end of your output is just garbage value which is printed just because printf could not find '\0' at the end of your string name1.
For name2 you used double quote to initialize the string which automatically puts a '\0' at the end of string.

Maximum number of elements that can be stored in an array in c

Please pardon me if it is a copy question. I will be happy to delete it if pointed out.
The question is that, if I declare a character array in c, say
char character_array[4];
Does that mean I can only store 3 characters and one '/0' is added as the fourth character? But I have tried it and successfully added four characters into the character array. But when I do that where is the '/0' added since I have already used up the four positions?
Well, yes, you can store any four characters. The string-termination character '\0' is a character just like any other.
But you don't have to store strings, char is a small integer so you can do:
char character_array[] = { 1, 2, 3, 4 };
This uses all four elements, but doesn't store printable characters nor any termination; the result is not a C string.
If you want to store a string, you need to accommodate the terminator character of course, since C strings by definition always end with the termination character.
C does not have protection against buffer overflow, if you aim at your foot and pull the trigger it will, in general, happily blow it off for you. Some of us like this. :)
You mix two notions: the notion of arrays and the notion of strings.
In this declaration
char character_array[4];
there is declared an array that can store 4 objects of type char. It is not important what values the objects will have.
On the other hand the array can contain a string: a sequence of characters limited with a terminating zero.
For example you can initialize the array above in C the following way
char character_array[4] = { 'A', 'B', 'C', 'D' };
or
char character_array[4] = "ABCD";
or
char character_array[4] = { '\0' };
or
char character_array[4] = "";
and so on.
In all these cases the array has 4 objects of type char. In the last two cases you may suppose that the array contains strings (empty strings) because the array has an element with zero character ( '\0' ). That is in the last two cases you may apply to the array functions that deal with strings.
Or another example
char character_array[4] = { 'A', 'B', '\0', 'C' };
You can deal with the array as if it had a string "AB" or just four objects.
Consider this demonstrative program
#include <stdio.h>
#include <string.h>
int main( void )
{
char character_array[4] = { 'A', 'B', '\0', 'C' };
char *p = strchr(character_array, 'C');
if (p == NULL)
{
printf("Character '%c' is not found in the array\n", 'C');
}
else
{
printf("Character '%c' is found in the array at position %zu\n",
'C',
(size_t)(p - character_array));
}
p = ( char * )memchr(character_array, 'C', sizeof(character_array));
if (p == NULL)
{
printf("Character '%c' is not found in the array\n", 'C');
}
else
{
printf("Character '%c' is found in the array at position %zu\n",
'C',
(size_t)(p - character_array));
}
}
The program output is
Character 'C' is not found in the array
Character 'C' is found in the array at position 3
In the first part of the program it is assumed that the array contains a string. The standard string function strchr just ignores all elements of the array after encountering the element with the value '\0'.
In the second part of the program it is assumed that the array contains a sequence of objects with the length of 4. The standard function memchr knows nothing about strings.
Conclusion.
This array
char character_array[4];
can contain 4 objects of type character. It is so declared.
The array can contain a string if to interpret its content as a string provided that at least one element of the array is equal to '\0'.
For example if to declare the array like
char character_array[4] = "A";
that is equivalent to
char character_array[4] = { 'A', '\0', '\0', '\0' };
then it may be said that the array contains the string "A" with the length equal to 1. On the other hand the array actually contain 4 object of type char as the second equivalent declaration shows.
You just reserve 4 bytes to fill with. If you write to _array[4] (the fifth character) you have a so called buffer overflow, means you write to non-reserved memory.
If you store a string in 4 characters, you have actually just 3 characters for printable characters (_array[0], ..., _array[2]) and the last one (_array[3]) is just for keeping the string termination '\0'.
For instance, in your case the function strlen() parses until such string termination '\0' and returns length=3.

How does the string populate an array

I'm creating a simple program to see how a string populates an array.
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
int main(void)
{
char string1[100];
int i;
printf("Enter sentence.\n");
fgets(string1, 100, stdin);
for (i=0; i<=15; i++)
puts(&string1[i]);
return 0;
}
I'm having a bit of a problem understanding how the string is populating an array. My expectation is that the string will be completely stored in string1[0] and any further indexes will come up blank. However, when I throw the loop to see if my assumption is true, it turns out that every index has been filled in by the string. Am I misunderstanding how the string is filling the array?
For the string "Hello!", the memory representation would be something like this
+-------+-------+-------+-------+-------+-------+-------+
| 'H' | 'e' | 'l' | 'l' | 'o' | '!' | '\0' |
+-------+-------+-------+-------+-------+-------+-------+
The first cell, at index 0, contains the first character. And each subsequent character is contained in a cell with an increasing index.
Library functions like puts expect you to pass the address of the first character, and then they read the string up to \0.
So if you pass simply string1 or &string1[0], it will resolve to the address of 'H'.
If you pass &string[1], it will resolve to the address of 'e', and the library function will think that is the first character, because that's the contract C strings are designed with.
Your problem is not string1 layout per se but how puts interprets it. Strings are represented by char arrays in C while their end is marked as null terminator (character with code 0):
S e n t e n c e \0
^ ^
string1 &string1[5]
&string1[5] is a pointer to a one character, but since the following character is not null terminator, following memory is interpreted as a string and nce gets printed.
You'll need to use putc and access individual characters:
putc(string1[i])
string is not stored in string1[0] but string's first character is stored at string1[0] or string starts at (string1+0). Here, &string1[0] or (string1+0) can be seen as a pointer, a pointer to C String string1.
In that sense, every valid index i of string1 will give you a valid pointer (string1 + i) which will point to some part of C String string1.
In the last for loop you are printing the suffixes of string string1 which are pointed by (string1 + 0), (string1 + 1), (string1 + 2)...

Resources