Why '&' isn't required for character data type? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why '&' isn't required for character data type?

In C Programming '&' isn't required for character/string data type. #include<stdio.h> int main () { char a; scanf("%c", a); printf("%c", a); return 0; }

30th Dec 2022, 2:21 AM
S M Rakibul Alam
S M Rakibul Alam - avatar
6 Answers
+ 3
Bob_Li That link actually wasn't helpful, atleast to someone who is clearly in the very early stages of programming. They clearly don't understand what pass by reference mean, and from their profile it doesn't even look like they've completed a course, so they might not even know what "passing to a function" even means. The code in the question was probably overwhelming for them too, so they might not even know what the SO question was about. There are many 'might's here and IMHO it's better to not just throw a link at someone and expect them to understand. Back to the question: S.M. Rakibul Alam '&' IS needed in scanf, and IS NOT needed in printf. You need to put a '&' before 'a' in the scanf call scanf("%c", &a); The scanf function needs to change the value at the memory location pointed by 'a'. If you don't pass a pointer, then the scanf function cannot change it (because a "copy" of 'a''s value is passed). If you haven't reached the topic of "pointers" yet, it will be clearer when you do.
30th Dec 2022, 7:00 AM
XXX
XXX - avatar
+ 3
(2/2) As for printf, you don't need to use a '&' because the character inside 'a' is copied and then given to printf for printing. This is because printf doesn't need to change 'a', it only needs it's value As for strings (char*), they are pointers themselves, so you don't need a '&' to pass them to scanf
30th Dec 2022, 7:02 AM
XXX
XXX - avatar
+ 2
if you read it the answers carefully instead of just skimming over it. you would understand why it is not needed🙄. if you can work with pointers, what's the need for addresses? copy pasting an excerpt: "Passing by reference literally just means passing the memory address of where a variable is stored rather than the variable's value itself. That is what C allows, and it is pass-by-reference every time you pass a pointer, because a pointer is a reference to a variables memory location."
30th Dec 2022, 3:10 AM
Bob_Li
Bob_Li - avatar
30th Dec 2022, 2:47 AM
Bob_Li
Bob_Li - avatar
0
Bob_Li.. that link wasn't helpful,.😓
30th Dec 2022, 2:50 AM
S M Rakibul Alam
S M Rakibul Alam - avatar
0
XXX thanks,,I know the topic 'pointer',,and I know the use of '&' ,,but I was confused about that topic,,
1st Jan 2023, 5:26 AM
S M Rakibul Alam
S M Rakibul Alam - avatar