What is the output of this C++ code? #include <iostream>using namespace std;void swap(int a,int b){ int temp = a; a=b; b=temp;}int main(){ int a = 1, b = 2; swap(a,b); cout<<a<<" "<<b; return 0;} 1 22 21 12 1
Question
What is the output of this C++ code? #include <iostream>using namespace std;void swap(int a,int b){ int temp = a; a=b; b=temp;}int main(){ int a = 1, b = 2; swap(a,b); cout<<a<<" "<<b; return 0;} 1 22 21 12 1
Solution
The output of the C++ code will be "1 2". This is because the swap function in the code does not actually swap the values of a and b in the main function. The swap function is swapping the values of its own local variables a and b, not the variables a and b defined in the main function. In C++, when you pass variables to a function, the function creates its own copy of those variables, and any changes made to the variables in the function do not affect the original variables. This is known as "pass by value". If you want the swap function to actually swap the values of a and b in the main function, you would need to pass the variables by reference, not by value.
Similar Questions
What is the output of the C Program?
What is the output for the following code?
What will be the output of the following C code?#include <stdio.h>int main() { int i; for (i = 0; i < 5; i++); printf("%d\n", i); return 0;}
What would be the output of the following program? #include <stdio.h> int main( ) { int j=1; while (j <= 255) { printf ( "%c %d\n ", j, j ); j++; } return 0; }
What is the output of this C code?#include <stdio.h>int main(){int a = 2;x = x << 1;printf("%d\n", a);}41Depends on the compilerDepends on the endianness of the machine
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.